Java file open and read example (Java FileReader, BufferedReader, and Java 5)

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?")

Here's a method taken from a Java class I wrote that shows how to open and read a file using Java and the Java FileReader class. This uses the most recent Java 5 syntax and classes.

Java open and read file example

In the following Java method, the 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>();
  try
  {
    BufferedReader reader = new BufferedReader(new FileReader(filename));
    String line;
    while ((line = reader.readLine()) != null)
    {
      records.add(line);
    }
    reader.close();
    return records;
  }
  catch (Exception e)
  {
    System.err.format("Exception occurred trying to read '%s'.", filename);
    e.printStackTrace();
    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.

This is quite th code... It

This is quite th code... It helped me a lot... Save me time in reading and manipulating files...
THANX A MILLION

Post new comment

The content of this field is kept private and will not be shown publicly.