How to read a text file in Java

Tuesday, April 15, 2008

Reading files from disk is an important and common task that is required in many programs. We’ll take a look at one way to read text files using Java.

Using the BufferedReader class

The package contains many input and output (I/O) classes. One useful class for reading text files is the class. It is particularly useful because of its BufferedReader.readLine() method, which allows for reading a line of text from a file. Another class that will be used is the class, which will read a specified file. The BufferedReader will be used as a wrapper to read the file one line at a time.

The following is an example of a program that reads the contents of a text file line-by-line and reads it into a String:


   * This program demonstrates how to read a text file.
   * @author coobird
  public class TextReadingApp {
  public static void main(String[] args) {
    // Will be used later to store the contents of a file.
    String contents= "";

    try {
      // A BufferedReader is instantiated with a newly instantiated
      // FileReader as its underlying reader.
      BufferedReader br = new BufferedReader(new FileReader("textfile.txt"));

      // A while-loop will continue to execute until the end of file
      // is reached, at which point br.ready() returns false.
      while (br.ready()) {
      // Concatenates the current line to another string.
      // The newline character is added, as the readLine()
      // method returns a String without the newline.
      contents += br.readLine() + "\n";
    } catch (FileNotFoundException e) {
      // Thrown by FileReader(String)
    } catch (IOException e) {
      // Thrown by br.ready()

    // Displays the contents of the file.

In the above program runs as follows: