File+IO+and+Serialization

**Chain/connection stream workflow for reading/writing strings**
(Chain) (Connection)

String <- BufferedReader <- FileReader <- File

String -> BufferedWriter -> FileWriter -> File All file operation objects are declared either with their destination file, or a File object pointing to the destination file, as a parameter. The File Class

• Can represent an existing file File f = new File("MyFile.txt")

• Can make a directory f.mkdir

• Can list directory contents f.list

• Can get the absolute path of a file or directory f.getAbsolutePath

• Can delete a file or directory f.delete The FileReader/FileWriter Class

• Can chain to a File object to find the file it needs FileReader reader = New FileReader(f)

• Reads/writes a string to a file writer.write("Text"); The BufferedReader/BufferedWriter Class

• Is an optional chain stream

• Makes file access more efficient by "buffering" data before it's used or written to disk

**Chain/connection stream workflow for serialized objects**
(Chain) (Connection)

Object -> ObjectOutputStream -> FileOutputStream -> File

Object <- ObjectInputStream <- FileInputStream <- File Serialized objects

• Must be based on objects declared serializable! public class TestClass implements Serializable

• Contain all data in an object except transient variables ObjectInput/OutputStream Class

• Used to convert an entire instance of a Java object into a raw binary data "stream."

• Can chain to a FileOutput/InputStreamObject so.readObject / so.writeObject FileInput/OutputSteam Class

• Used to "stream" raw binary data into or out of a file Final Notes

• All file operations must be written in try/catch form.

• When a file is read/streamed it is from beginning to end.

• When the end of the file is reached, an exception is generated that must be caught.

• Exceptions can be thrown at just about any other time.

• FileRead/Write and ObjectInput/OutputSteams must be closed when finished.

• If a file described in one of those objects does not exist, it will be created automatically.