FAQ: How do I read text from a text file?

By Alvin J. Alexander, devdaily.com

FAQ: Using Java, how do I read text from a text file?

Answer: Just use a FileReader and a BufferedReader, then read from the using the convenience methods of the BufferedReader class.

The complete example Java program shown below demonstrates this. Here I'm reading a text file from my home directory, and writing the contents of that file out to standard output. Note that a FileNotFoundException and a IOException can be thrown during this process, as shown in the sample code.

package com.devdaily.javasamples;

import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;

/**
 * Demonstrates how to read text from a text file using Java.
 * Created by Alvin Alexander, http://devdaily.com.
 */
public class JavaReadTextFromAFileExample
{

  public static void main(String[] args)
  {
    BufferedReader br = null;
    try
    {
      br = new BufferedReader(new FileReader("/Users/al/HelloWorld.txt"));
      String line = null;
      while ( (line = br.readLine()) != null )
      {
        System.out.println(line);
      }
    }
    catch (FileNotFoundException e)
    {
      // can be thrown when creating the FileReader/BufferedReader
      // deal with the exception
      e.printStackTrace();
    }
    catch (IOException e)
    {
      // can be thrown by br.readLine()
      // deal with the exception
      e.printStackTrace();
    }
  }

}

devdaily logo