Chapter 8: Files and Directories Flashcards
File class
Can be used to represent directories as well
constructor takes either a single String with entire path or a parent and a child string
Common methods:
.length() = num bytes
.delete() = deletes file or directory (only if directory is empty)
.mkdir() = makes directory
.getParent() = null if path name does not have a parent
.listFiles() = File[] of files in directory
.renameTo()
.mkdirs()
Byte streams vs Character streams
InputStream/OutputStream used for binary or byte data
InputReader/OutputWriter etc used for character/string data.
Mostly an input class with have a corresponding output class and reader class will have a writer class. Apart from PrintWriter and PrintStream
Directory structures
Windows \
Linux /
Low-level vs high-level classes
Low level classes e.g. FileReader or FileInputStream interact with data directly. High-level classes wrap around low-level classes (by passing an instance to a constructor)
High level streams improve performance. E.g. BufferedInputStream or ObjectInputStream
Stream operations
.flush()
all accumulated data is written to disk (e.g. when system terminates and some data is yet to be written)
when you close a resource it will call flush()
InputStream .mark()
Need to check .markSupported() to check that you can actually use this, otherwise it might throw a RunTimeException –> check for this in the exam!
.mark(int) to mark a point in a stream, you can then read-ahead to the limit (the it value)
You can then .rest() to reset back to the marked point and you can read it all over again/
If you’ve gone over the read-ahead limit, it may throw an Exception if you try to reset.
Can call .skip(int) to skip over int number of bytes.
Working with streams
FileInputStream: .read() method returns -1 if the end of the file has been reached. FileInputStream takes a File object in constructor, needs to know where the location of the file it is reading from otherwise it can throw FileNotFoundException.
FileOutputStream .write(int) or write(bytearray) writes to an output stream.
Buffered classes
BufferedInputStream/BufferedOutputStream wraps around FileInputStream/FileOutputStream.
in.read(buffer) buffer is a byteArray of size n (number bytes it reads in at a time)
Returns an int indicating how many bytes were read.
If 0 then you’ve reached the end of the File.
out.write(buffer, int start to write from, int length how many bytes to write)
then call out.flush() to make sure it’s all written
BufferedReader (wraps FileReader)
reader.readLine(), returns null if no line to read. returns a String if there is a line to read.
BufferedWriter (wraps FileWriter)
writer. write(String)
writer. newLine() -> line break
writer. append(line). Throws IOException.
Character encoding
Can get a Charset using Charset.forName(“UTF-8”)
Serializable class
Serialization is the process of converting an in-memeory object into a stored data format on disk. Needs to implement Serializable. -> indicates all instance variables should be marked Serialzable. -> If a class does not properly implement Serializable it will throw a NotSerializableException -> If one of the properties doesn't implement Serializable but you don't care about it, you can add the transient keyword to it & and it will be ignored -> Static variables aren't stored (if it needs to be stored you need to copy it to an instance variable) -> Recommended to add serialVersionUID to this is used to uniquely identity the version of the class (if an older version is encountered it may throw an Exception)
Serializing/Deserializing
Reading from disk.
Use new ObjectInputStream(new BufferedInputStream(new FileInputStream(File)))
in.readObject() returns a type of Object. Need to cast down at RunTime (watch out for ClassCastException)
Can use instanceof to determine if is instanceof (will also handle null values)
Throws EOFException when you get to end of File (need to swallow this Exception)
Writer to disk
new ObjectOutputStream(new BufferedOutputStream(new FileOutputStream(File))
writer.writeObject(object)
Object creation from deserializing an object
Java calls the first no-arg constructor for the first non-serializable parent class, skipping the constructors of any serialized Objects in between.
Static, transient variables ignored and initializations ignored.
When Java constructs it will use JVM default initialisations e.g. null for Objects
static variable gets the last value shared across all objects at the point when it gets created (e.g. if it had a different variable before, it wouldn’t have that now).
PrintStream and PrintWriter
Write Java Objects to a text-based output stream. PrintWriter writes String data as Characters rather than bytes. .print() calls String.valueOf() and then .write() .println() adds a linebreak after value is written .format() /.printf() writes a formatted String Can do new PrintWriter("path/to/file") or new PrintWriter(new BufferedWriter(new FileWriter()))
Interacting with Users
java.io.Console is the recommended way to interact with users.
Console is a singleton, will be null if text-based system is not support.
.reader()/.writer() provides access to an instance Reader and PrintWriter.
better than System.in/System.out as those use InputStream and OutputStream. so console deals with text better and handles character encoding automatically.
.format()/printf()
Note if you want to pass a Locale variable, need to use the .writer() method from console e.g. console.writer().format(Locale , …)
.flush()
Ensures any buffered output is written immediately.
Best to call flush() prior to calling any readLine() or readPassword() methods so no data is pending.
.readLine() reads a single line of input from user, user terminates using carriage return.
.readPassword()
echoing is disabled so doesn’t display on screen.
Returns an array of chars, so that String doesn’t go to pool and get saved to desk etc.
You can then wipe the data by overwriting the values in the array.
Can call .readLine or .readPassword() without calling .reader() from console object.