How to read a file line by line in Java?

In Java, you can use BufferedReader to read a file line by line. Here is a simple example:

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

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

In this example, we start by creating a BufferedReader object to read the file “file.txt”. We then use a while loop to read the file content line by line until the end. Once we read each line, we output it to the console.

It is important to note that when dealing with file reads, it is essential to remember to handle potential exceptional cases by processing them in a try-catch block.

bannerAds