Reading A Text File Line By Line In Java With Example

In this post, I am going to give you Java code snippet which will read a text file line by line. In this Java tutorial, I am going to use the BufferedReader Java class.

It is going to be an easy tutorial. Reading a text file line by line using Java Programming language is quite easy. Below is the given code which will do the task:

At first, suppose our text file is exampletextfile.txt. Below is the given code which will read this text file:

package test;


public class ReadTextFileLineByLine {

  public static void main(String[] args) {
    try {
      File file = new File("exampletextfile.txt");
      FileReader fileReader = new FileReader(file);
      BufferedReader bufferedReader = new BufferedReader(fileReader);
      StringBuffer stringBuffer = new StringBuffer();
      String line;
      while ((line = bufferedReader.readLine()) != null) {
      System.out.println("Contents of file:");
    } catch (IOException e) {

In the above code will read the exampletextfile.txt file using FileReader. The BufferedReader read the file line by line and each line is appended as StringBuffer. It is followed by a linefeed.

To test the code create a text file and add the path in this code. When you run the Java program, you will see the text appearing line by line as it is in the text file.

Leave a Reply

Your email address will not be published. Required fields are marked *