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

In this java program, we will learn to read the content of a file line by line. In Java, you can read the content of a file line by line using the BufferedReader class. The BufferedReader class reads text from a character-input stream and provides a convenient method called readLine() which reads a line of text.

Here is an example of how you can read the content of a file line by line in Java.

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

public class FileReadExample {
  public static void main(String[] args) {
    String fileName = "example.txt";
    try (BufferedReader reader = new BufferedReader(
            new FileReader(fileName))) {
      String line;
      while ((line = reader.readLine()) != null) {
        System.out.println(line);
      }
    } catch (IOException e) {
      e.printStackTrace();
    }
  }
}
Output
Hello World!

In this example, the main method first creates a BufferedReader object and uses it to read the file named "example.txt" line by line. The readLine() method returns a string containing the next line of text from the file, or null if the end of the file has been reached. The while loop iterates over the file, and for each iteration, it prints the line of text to the console.

You can also use other classes like FileInputStream or Scanner to read the content of a file. FileInputStream reads bytes, it's useful when you want to read a binary file, while Scanner class can be used to tokenize the data and read it in a more structured way.