Java Line Count for File

Line count. A text file has line separators in it. With a method like readLine on BufferedReader, we can count these lines in a file.
With readLine, we can handle all kinds of newline sequences (UNIX and Windows) with no effort on our part. A BufferedReader can be made from a Reader instance (like FileReader).
Our example. This program might throw an IOException, so it has the "throws IOException" notation at its top. It includes classes from the namespace.

ReadLine: This method returns null when no more lines exist in the file (at end-of-file). We call it repeatedly.

LineCount: This int is incremented on each valid line read—when readLine does not return null.

Important: Make sure to change the file name passed to FileReader to one that exists on your system.

Java program that counts lines in file import; import; import; public class Program { public static void main(String[] args) throws IOException { int lineCount = 0; // Get BufferedReader. BufferedReader reader = new BufferedReader(new FileReader("C:\\programs\\example.txt")); // Call readLine to count lines. while (true) { String line = reader.readLine(); if (line == null) { break; } lineCount++; } reader.close(); // Display the line count. System.out.println("Line count: " + lineCount); } } Contents of example.txt: HELLO FROM DOT NET PERLS Output Line count: 3
Notes, in-memory files. For a file that is resident in memory, we can use a for-loop and scan for a known newline character. This would be faster than loading it from disk.For
A summary. Sometime simple is best. Many line-counting methods can be used. We could even cache a file's line count as it is read in, and then retrieve that value when needed.
© 2007-2020 Sam Allen. Every person is special and unique. Send bug reports to
Dot Net Perls