5. I/O & NIO Flashcards

1
Q

What is the File class?

A
the file class isn’t used to actually read or write data; its used to work at a higher level,
making new empty files, searching for files, deleting files, making directories en working with
paths.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

What is the FileReader class?

A
this class is used to read character files. Its read() methods allowing you to read
single characters, the whole stream of characters or a fixed number of characters.
FileReaders are wrapped by higher-level objects (BufferedReaders)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

What is the BufferedReader class?

A

this class is used to make lower-level Reader classes (FileReader) more
efficiënt and easier to use. BufferedReaders read relatively large chunks of data from a file at
once and keep this data in a buffer.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

What is the FileWriter class?

A
this class is used to write to character files. Its write() allow you to write
characters or strings to a file. These are wrapped by higher-level writer objects
(BufferedWriters or PrintWriters)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

What is the BufferedWriter class?

A
this class is used to make lower-level Writer classes (FileWriter) more
efficiënt and easier to use. It writes relatively large chunks of data to a file at once.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

What is the PrintWriter class?

A

because of newly created methods and contructors you might find that you can
use PrintWriter in places where you previously needed a wirter to be wrapped. New
methods make printwriter quite flexible and powerful

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is the FileInputStream class?

A
this class is used to read bytes from files and can be used for binary as well
as tekst. We use FileInputStream with higher-level objects (ObjectInputStream)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

What is the FileOutputStream class?

A
this class used to write bytes to files. We use FileOutputStream with higher-
level objects (ObjectOutputStream)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

What is the ObjectInputStream class?

A
this class is used to read an input stream and deserialize objects. Its
used with FileOutputStream so that you can read objects rather than characters or bytes.
This proces is called deserialisation
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

What is the ObjectOutputStream class?

A
this class is used to write objects to an ouput stream and is used with
classes like FileOutputStream to write to a file (serialization)
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

What is the Console class?

A
this class provides methods to read input from the console and write formatted
output to the console.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

What are Objects of type File representing?

A

Objects of type File are used to represent the actual files(but not the data in the files) or directories that exist on a computers physical disk.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
13
Q

Does new File(); creates a file?

A

No

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
14
Q

What does boolean createNewFile(); do?

A

Returns true if the named file does not exist and was successfully created; returns cals if the named file already exist

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

What does boolean exists(); do?

A

The exists() look if the named file already exists

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
16
Q

What does the code FileWriter fw = new FileWriter(file); do?

A

does two things:

  • It created a FileWriter reference variable (fw), and a FileWriter object, then assigned to fw
  • It created an actual empty file out on the disk
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
17
Q

What happens when you write data out to a stream?

A

When you write data out to a stream, some amount of buffering will occur, and you never know for
sure exactly when the last data will actually be sent.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
18
Q

What does the flush() method do?

A

invoking the flush() method guarantees that the last of the data you thought you had already written actually gets out to the file.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
19
Q

What does the close() method do?

A

Whenever you’re done using a file you should invoke the close() method. This method has following
results:
- If the stream is open, it closes the stream releasing the resources
- If the stream is already closed, it will have no effect.
- If any read or other similar operation is performed on the stream, after closing, it raises
IOException

20
Q

What are 2 ways to create a file?

A
  • Invoke the createNewFile() method on a File object.
  • Create a Writer or a Stream. Specifically, create a FileWriter, Printwriter or a
    FileOutputStream. Whenever you create an instance of one of these classes, you
    automatically create a file, unless one already exists.
21
Q

How to create a directory?

A

Creating a directory is similar to creating a file. As with creating a file, creating a directory is a 2-step
process; first we create a Directory (File) object, then we create an actual directory using the mkdir()
method.

22
Q

What do you need to keep in mind with directories?

A

Be careful when you’re creating new directories! As we have seen, constructing a Writer of a Stream
will often create a file for you automatically if one doesn’t exist, but that is not true for a directory. If
you omit to call mkdir() method no directory will created

23
Q

What does readLine() returns?

A

When there is no more data to read, readLine() returns a null – this our signal to stop reading the file.
When reading a file no flushing (flush()) is requires.

24
Q

What are the rules for the delete and renaming methods in File?

A

The File class lets you do things like renaming and deleting files. Most common ins and outs of
deleting files and directories (via delete()) and renaming files and directories (via renameTo()). Here
are some rules for it:
- delete(): you cannot delete a directory if it is not empty
- renameTo(): You must give the existing File object a valid new File object with the new name
that you want (if newName had been null, we would have gotten an NullPointerException())
- renameTo(): its okay to rename a directory, even it isn’t empty

25
Q

What does the File.list() method do?

A

This method returns a string array of files and
directories. We then use the enhanced fo loop to iterate through and print. If you leave the path
section empy -> NullPointerException()

26
Q

When do you have a Console Object?

A

If you are running Java from the command line, you will have access to a console object, to which you
can get a reference by invoking System.console() (this method returns – if found – a valid console
reference, if you don’t run it from the command line or it can’t find a console -> null)

27
Q

what does the readLine() method do?

A

returns a string containing whatever the user keyed in.

28
Q

what does the readPassword() method do?

A

returns a character array. (not a String cause once you have got the password, you can verify it and then absolutely remove it from memory. If a string was
returned, it could exist in a pool somewhere in memory, and a hacker could find it

29
Q

What is the Path interface?

A

this interface is one of the key classes of file-based I/O under NIO.2 and replaces File as the representation of a file or a directory when working in NIO.2. It is a lot more powerful than a File

30
Q

What is the Paths class?

A

this class contains static methods that create Path objects

31
Q

What is the Files class?

A

this class contains static methods that work with Path objects. You will find basic operations in here like copying or deleting files.

32
Q

Does the file automatically be created when creating a new Path?

A

When you create a Path to a new file, that file does not exist until you actually create the file using
Files.createFile(Path target).

33
Q

What are 2 different paths?

A
  • Absolute path: since they begin with the root (c: = windows, / = linux).
  • Relative path: when you do not begin with the root, which means java looks from the current
    directory.
34
Q

What is the file://c:/ws. syntax?

A

If you are on windows you might deal with a URL that looks like file://c:/ws. The file:// is a protocol
(such as http). This syntax allows you to browse to a folder in internet explorer. But you can only use
these syntax this way: convert the String to a URI, before trying to create a Path:

Path p = Paths.get(URI.create(file:///C:/ws));

35
Q

What are the copy() and move() methods?

A

If you try to overwrite a file that already exists, java doesn’t want us to lose the file, so it “asks” if we
are sure by throwing an exception. Copy() and move() actually take an optional third parameter –
CopyOptions (vb. StandardCopyOption.REPLACE_EXISTING – you tell your jvm, I know what i’m
doing).

36
Q

What happens if you try to delete a file that don’t exist?

A

If you try to delete a file that don’t exist, you get a NoSuchFileException. There is an alternative,
Files.deleteIfExists(path) returns true and deletes the file only if it exists. If not, it just quietly returns
false.

37
Q

What are the important methods in the File class to know?

A

Method Description
- Path copy(Path source, Path target, CopyOption…
option)

Copy the file from source to target and return
target

  • Path move(Path source, Path target, CopyOption…
    options)

Move the file from source target and return target

  • void delete(Path path)

Delete the file and throw an exception if it does
not exist

  • boolean deleteIfExists(Path path)

Delete the file if it exists and return whether file
was deleted

  • Boolean exists(Path path, LinkOption… options)

Return true if file exists

  • Boolean notExists(Path path, LinkOption…
    options)

Return true if file doesn’t exists

38
Q

What are the important methods in the Path class to know?

A
  • String getFileName()
    Return the filename or the last element of the sequence of name elements
  • Path getName(int index)
    Return the path element corresponding to the
    specified index. The 0th element is the one closest
    to the root (C:\ or /) (Throws
    illegalArgumentException if its out of bound).
  • int getNameCount()
    Returns the number of elements in this path, excluding the root
  • Path getParent()
    Returns the parent path, or null if this path does not have a parent
  • Path getRoot()
    Return the root of this path, or null if this path does not have a root
  • Path subPath(int beginIndex, int endIndex)
    Returns a subsequence of this path (not including
    the root element) as specified by the beginning
    (included) and ending (not included) indexes.
    (Throws illegalArgumentException if its out of
    bound).
  • String toString()
    Returns the string representation of this path
39
Q

What are the NIO.2 attributes?

A
  • BasicFileAttributes: You can rely on these attributes being available to you unless you are
    writing java code for some new funky operating system. Attributes common to many file
    systems
  • PosixFileAttributes: This interface is implemented by both UNIX- and Linux-based operating
    systems. (ezelsbruggetje: Posix eindigd met x net als UNIX en Linux)
  • DosFileAttributes: This interface is part of all Windows operating systems.
40
Q

Which methods do the BasicFileAttributes interface provide?

A
  • DateTime creationTime()
  • DateTime lastAccessTime()
  • DateTime lastModifiedTime()
  • Boolean isDirectory()

The key takeaway here are that the FileAttributes classes are read only and the FileAttributeView
classes allow updates.

41
Q

What is the directoryStream interface?

A

The directoryStream interface lets you iterate through a directory. You can filter data when iterating
through a directory with DirectoryStream as follows:
DirectoryStream stream = Files.newDirectoryStream(dir, “[vw]*”);
[vw] means either of the character v or w. The * is a wildcard that means zero or more of any
character. There is one limitation with DirectoryStream. It can only look at one directory
(ezelsbruggetje: werkt net als dir in de cmd, en directoryStream directory is enkelvoud).

42
Q

What does the FileVisitor class do?

A
class that does, in fact, look at subdirectories. Java provides a SimpleFileVisitor class. You extend it and override the method visitFile(). Then you can call
Files.walkFileTree(Path path, FileVisitor visitor), which knows how to recursively look through a
directory structure and call methods on a visitor subclass. See blz 289 for a code example.

There are 2 parameters to visitFile()

  • Path file: the Path object representing the current file.
  • BasicFileAttributes: it lets you find out if the current file is a directory, and many other similar
    pieces of data
Finally visitFile() returns FileVisitResult.CONTINUE this tells walkFileTree() that it should keep looking
through the directory structure for more files.
43
Q

What are the 4 different FileVisitResult constant?

A
  • CONTINUE: Continue
  • SKIP_SUBTREE: Continue without visiting the entries in this directory
  • TERMINATE: Terminate, hij stopt gwn met walktreeën net als system.exit doet ook geen post
    dingen meer
  • SKIP_SLIBBINGS: combination of SKIP_SUBTREE and “don’t look in any folders at the same
    level”
44
Q

Gouden regel FileVisitor

A

File visitor can only skip subtrees that it has not encountered yet.

45
Q

What does serialisation do?

A

When you serialize an object, java serialization takes care of saving that object’s entire “object
graph”. That means everything the saved object needs to be restored (also the object that the
reference refers to). But these reference classes must also implement the Serializable interface.

46
Q

What does the transient keyword do?

A
You can also mark the instance reference variable with transient, then serialization will simply skip
the reference class during serialization. That means when the class is serialized, the reference
variable value will be null.
47
Q

Can a subclass be serializable? when the super class is not?

A
What happens if a superclass is not marked Serializable, but the subclass is? This works, but there are implications. The instance variables from the subclass will be serialized an deserialized correctly, but
the inherited variables from the non-serializable superclass will come back with their default values.
This is because the non-serializable class constructor will run.