Java program to count number of lines present in the file

Here's a Java program to count the number of lines in a file:

ref‮:ot re‬theitroad.com
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CountFileLines {
    public static void main(String[] args) {
        try {
            // Create a file reader and buffered reader to read the file
            FileReader fileReader = new FileReader("filename.txt");
            BufferedReader bufferedReader = new BufferedReader(fileReader);
            
            int lineCount = 0;
            
            // Read each line of the file and increment the line count
            while (bufferedReader.readLine() != null) {
                lineCount++;
            }
            
            // Close the readers
            bufferedReader.close();
            fileReader.close();
            
            // Print the line count
            System.out.println("Number of lines in the file: " + lineCount);
            
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

This program uses a FileReader and a BufferedReader to read the lines of a file. It then uses a while loop to read each line of the file and increment a line count variable. After all lines have been read, the readers are closed, and the line count is printed to the console.

Note that in this program, we have used a try-catch block to handle any IOException that might occur while reading the file. It's always a good idea to handle exceptions when reading files to ensure that your program doesn't crash if there is an error.