Count Lines in File Java: BufferedReader Example

In Java, you can use the BufferedReader class to read a file and use a loop to read the file content line by line and count the number of lines. Below is an example code:

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

public class Main {
    public static void main(String[] args) {
        String filePath = "path/to/your/file.txt";
        int lineCount = 0;

        try {
            BufferedReader reader = new BufferedReader(new FileReader(filePath));
            while (reader.readLine() != null) {
                lineCount++;
            }
            reader.close();
        } catch (IOException e) {
            e.printStackTrace();
        }

        System.out.println("Number of lines in the file: " + lineCount);
    }
}

In the code above, first specify the file path to be read, then use the BufferedReader class to create a file reader. Then, within a loop, read the contents of the file line by line using the readLine() method until the end of the file is reached. Increment the line number for each line read. Finally, output the total number of lines in the file.

Please note that when using the BufferedReader class to read a file, it is necessary to handle any potential IOException exceptions in the code.

bannerAds