Java program to read the content of a file line by line

ww‮gi.w‬iftidea.com

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) {
        String fileName = "example.txt";
        try {
            BufferedReader reader = new BufferedReader(new FileReader(fileName));
            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
            reader.close();
        } catch (IOException e) {
            System.err.println("Error reading file: " + e.getMessage());
        }
    }
}

This program reads the contents of a file named "example.txt" and prints each line to the console. The BufferedReader class is used to read the file, and the readLine() method is used to read each line of the file one at a time. The while loop continues until the end of the file is reached (readLine() returns null). If there is an error reading the file, an error message is printed to the console. The file name can be changed to read the contents of a different file.