Input - Output
Quiz
- Which classes do you use to Read a File line by line? Why?
- Which classes do you use to Write on a File line by line? Why?
- Which exceptions do you care about when working with Files? Why?
- What are the data access layer principles?
Approaches to Object Persistence
When a Java program is executed, all the Objects that we instantiate reside in memory allocated to the JVM. If the program terminates all the data and state related to the objects will be forgotten. On the other hand we can persist the data save it:
- JDBC => Database storage
- Binary Large Object (Blob)
- Output in Java serialized object
- String human readable
- XML
- etc.
Data Access Layer Principles
- Hiding the details of how we persist an object
- Adhering to the design principle of model–data access layer separation.
- Flexibility, in order to change the storage strategy.
- Providing graceful error handling.
The Basics of File I/O in Java
Reading from a File
- Instantiate
FileReader
, it knows how to open a file and read it character by character. - Instantiate
BufferedReader
, it knows how to read a file line by line using theFileReader
.
BufferedReader bIn = new BufferedReader(newFileReader(nameOfFileToBeReadFrom));
- Read until the end fine, that means that the current line is
null
.
// As long as the end of the file hasn't been reached ...
while (line != null) {
// Processing details omitted ...
// Remember to read another line, to avoid an infinite loop!
line = bIn.readLine();
}
- Close stream
bIn.close();
Writing to a File
- Instantiate
FileOutputStream
, it knows how to open a file and write on it character by character. - Instantiate
PrintWriter
, it knows how to write on a file line by line using theFileOutputStream
.
PrintWriter pw = new PrintWriter( new FileOutputStream(nameOfFileToBeWrittenTo));
- Close stream
pw.close();
, this statement will flush the data into the file. - If the file does not exist a new file will be created.
- If append flag is not use it, the process will override the file.
Exception Handling with File I/O
The RunTimeExceptions
are common in this type of processes.
FileNotFoundException
IOException
=> General problem