How can Java read file contents line by line?

In Java, we can use the BufferedReader class to read the contents of a file line by line. Here is an example code:

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

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

In this example, we begin by creating a BufferedReader object and passing in a FileReader object to read a file. We then use a while loop to read the file line by line and output each line to the console. Finally, remember to close the file stream to release resources.

bannerAds