Write a Java Program to Read the Content of a File Line by Line

Reading the contents of a file line by line is a common task in Java programming.

In this tutorial, we will walk through how to read the contents of a file line by line using Java programming.


To read the contents of a file line by line, we first need to create an instance of the FileReader class.

The FileReader class is used to read characters from a file, and it takes a file name or file object as its input.

Next, we need to create an instance of the BufferedReader class.

The BufferedReader class is used to read text from a character-input stream, and it provides a method for reading a line of text.

Once we have created the FileReader and BufferedReader objects, we can use the readLine() method of the BufferedReader class to read the contents of the file line by line.

The readLine() method returns a String object containing the text of the current line.

Here’s an example Java program that reads the contents of a file line by line:

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

public class ReadFileLineByLine {

    public static void main(String[] args) {

        try {
            // Create FileReader object
            FileReader fileReader = new FileReader("file.txt");

            // Create BufferedReader object
            BufferedReader bufferedReader = new BufferedReader(fileReader);

            // Read file line by line
            String line;
            while ((line = bufferedReader.readLine()) != null) {
                System.out.println(line);
            }

            // Close resources
            bufferedReader.close();
            fileReader.close();

        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

In the above example, we create a FileReader object with the name of the file we want to read.

We then create a BufferedReader object using the FileReader object.

Finally, we use a while loop to read the contents of the file line by line using the readLine() method of the BufferedReader object.

We also need to close the BufferedReader and FileReader objects to release the resources they are using.

We do this in a try-catch block to handle any exceptions that may occur during the file reading process.


In conclusion, reading the contents of a file line by line is a simple task in Java programming.

By using the FileReader and BufferedReader classes, we can easily read the contents of a file line by line and perform any necessary operations on each line.