The most flexible way to read files in Java involves using a sort of Russian doll system of objects; in this tutorial we'll look at reading text files using such a method. Unfortunately prior to Java 7 we end up using a bizarre and byzantine system of exceptions too, but Java 7 fixes that, as we'll see in the next tutorial.

When the video is running, click the maximize button in the lower-right-hand corner to make it full screen.

Code for this tutorial:

App.java:

importjava.io.BufferedReader;importjava.io.File;importjava.io.FileNotFoundException;importjava.io.FileReader;importjava.io.IOException;publicclassApp{publicstaticvoidmain(String[]args){Filefile=newFile("test.txt");BufferedReaderbr=null;try{FileReaderfr=newFileReader(file);br=newBufferedReader(fr);Stringline;while((line=br.readLine())!=null){System.out.println(line);}}catch(FileNotFoundExceptione){System.out.println("File not found: "+file.toString());}catch(IOExceptione){System.out.println("Unable to read file: "+file.toString());}finally{try{br.close();}catch(IOExceptione){System.out.println("Unable to close file: "+file.toString());}catch(NullPointerExceptionex){// File was probably never opened!}}}}