Java I/O How to - Reads a text file and displays it line by line








Question

We would like to know how to reads a text file and displays it line by line.

Answer

/*  www  .j ava  2 s. c o  m*/

import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;

public class MainClass {
  public static void main(String[] a) {

    FileReader fr;
    try {
      fr = new FileReader (new File("yourFile.txt"));
      BufferedReader br = new BufferedReader (fr);
      String line = br.readLine();
      while (line != null) {
          System.out.println(line);
          line = br.readLine();
      }
      br.close();
      
    } catch (Exception e) {
      // TODO Auto-generated catch block
      e.printStackTrace();
    }
  }
}

The code above generates the following result.