Read Text File Line by Line in Java

To read a text file line by line in Java, you can use the FileReader and BufferedReader classes.

Firstly, you need to create a FileReader object and pass the txt file you want to read as a parameter to it. Then, create a BufferedReader object and pass the FileReader object as a parameter to it.

Next, use the readLine() method from BufferedReader to read the content of the txt file line by line. This method reads one line at a time and returns a string. If it reaches the end of the file, the readLine() method will return null.

Here is an example code for reading a txt file line by line:

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

public class ReadFile {
    public static void main(String[] args) {
        BufferedReader reader = null;

        try {
            reader = new BufferedReader(new FileReader("file.txt"));

            String line;
            while ((line = reader.readLine()) != null) {
                System.out.println(line);
            }
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            try {
                if (reader != null) {
                    reader.close();
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

Please note to replace “file.txt” in the above code with the actual file path you want to read.

bannerAds