File I O And Exceptions

File I/O

Java I/O works via a stream: a connection to a source of data. This connection could be to

  • Files

  • Keyboard input

  • Etc.

To perform I/O at a high-level, these are the steps:

  1. import java.io.*;

  2. Open a stream

  3. Use the stream (read, write, or read-write)

  4. Close the stream

Reading with FileReader and BufferedReader

// 1. Import
import java.io.*;

// 2. Open stream
File myFile = new File(pathToFile);
FileReader fileReader = new FileReader(myFile);
BufferedReader bufferedReader = new BufferedReader(fileReader); // buffered version

// 3. Use stream
String s = bufferedReader.readLine(); // returns null if nothing more to read

// 4. Close stream
fileReader.close();
bufferedReader.close();

Reading with Scanner

Writing with FileWriter and PrintWriter

Writing with FileWriter and BufferedWriter

Exceptions

Errors are actual bugs in your program:

  • Going out of bounds of array

  • Trying to use a null reference

Exceptions, on the other hand, have to do with causes outside of your program:

  • Trying to read a file that doesn't exist

  • Running out of memory

Because exceptions aren't necessarily your fault, often times the best thing you can do is write your code in such a way that catches and handles those exceptions.

Try, catch, finally pattern

Java has a control flow for catching and handling exceptions:

Note: The finally block even runs when you provide a return statement in the other blocks!

Passing the buck

Sometimes you don't want to be handling the exception yourself because you want the caller of the method to handle the exception themselves.

What you can do when defining a method that can generate an exception is to include a throws keyword:

Last updated