IO Flashcards
File class
used to read information about existing les and directories, list the contents of a directory, and create/delete les and directories.
Two ways to retrieve the file separator character for the current file system
System.getProperty(“file.separator”)
java.io.File.separator
What does the following code do?
File file = new File("/home/smith/data/zoo.txt"); System.out.println(file.exists());
Checks if the file exists within the file system.
How to create a new File object
File file = new File(String path);
Difference between the “Stream” named classes and the “Reader/Writer” classes
The stream classes are used for inputting and outputting all types of binary or byte data, whereas the reader/writer classes can only work with characters and strings
What does it mean when a class has the word “Buffered” in it?
The class reads and writes data in groups rather than a single byte or character at a time.
Unless you are doing something very specialized in your application, you should always wrap a file stream with a Buffered class in practice.
You create these instances by wrapping the corresponding stream type, which means, for example, that if you had a BufferedWriter, you would create it with: new BufferedWriter(new FileWriter(filename))
Where should you open your file streams?
In the opening of a try-with-resources statement so that it will close at the end. Otherwise you must call .close() on it when you are done
flush()
When called on a stream, requests that all accumulated data be written immediately to disk.
Useful for if the application terminates unexpectedly
What should you do before calling the mark(int) method on a stream?
Call markSupported() on the stream to make sure it supports mark(int). Otherwise an exception will be thrown if it doesn’t support it.
mark(int num)
Sets a marker at the current point in the stream and allows you to read up to num amount of bytes with the ability to call reset() if you want to return to the original marked point
skip(long num)
Skips over the next num bytes, or if there are less than num bytes left then skips to the end.
Returns the number of bytes skipped.
How do you know when a FileInputStream object has reached the end of the file?
It returns -1
What exception is thrown if the file you try to read from doesn’t exist?
FileNotFoundException
copy(File file1, File file2)
Copies the contents of file1 to file2, overwriting any content that file2 may already have
write(byte[],int,int)
Used with BufferedOutputStream, stores the bytes in the byte array until filled with the third arguments value of bytes. The second argument is an offset to start writing which is usually set to 0