Java: How to open and read a text file with FileReader and BufferedReader

Java File I/O FAQ: How do I open a file and read text from it using Java? (Also written as, “How do I use the Java BufferedReader and FileReader classes to read from a text file?”)

Solution: Here’s a method taken from a Java class I wrote that shows how to open and read a file using the Java FileReader class.

Java file: open and read example

In the following Java method, a text file is opened with the Java FileReader and BufferedReader, and then, as each line of the file is read it is assigned to a Java String, with each String in turn being added to an ArrayList named records.

 * Open and read a file, and return the lines in the file as a list
 * of Strings.
 * (Demonstrates Java FileReader, BufferedReader, and Java5.)
private List<String> readFile(String filename)
  List<String> records = new ArrayList<String>();
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = reader.readLine()) != null)
    return records;
  catch (Exception e)
    System.err.format("Exception occurred trying to read '%s'.", filename);
    return null;

Note that when I read and open the file, I just catch any errors that may occur with a generic Exception object, but if you need to handle more specific problems you can catch the individual IOException and FileNotFoundException objects.

(As a side note, if you're interested in formatting your text output, note that I use System.err.format to print my error output.)

Opening a text file with Java

As you can see from the example, I open the text file using this line of code:

BufferedReader reader = new BufferedReader(new FileReader(filename));

You want to use both a BufferedReader and FileReader like this when reading from a text file in Java. I don't know why a FileReader doesn't handle buffering, but it doesn't, so you add the BufferedReader to make it much faster to read larger files. The BufferedReader also gives you the convenient readLine method. For more information about this, see my Java FileReader examples/tutorial and my Java BufferedReader examples.

You can also use some methods of the Java File class to test that the file exists and is readable, but I've skipped those steps in this example, as those problems will be caught with the try/catch statement.

Java file read and open example - Summary

I hope this Java file-open and file-read example has been helpful. If you have any questions, just leave a note in the Comments section.