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
).
This program might throw an IOException
, so it has the "throws IOException
" notation at its top. It includes classes from the java.io
namespace.
null
when no more lines exist in the file (at end-of-file). We call it repeatedly.int
is incremented on each valid line read—when readLine
does not return null
.FileReader
to one that exists on your system.import java.io.BufferedReader; import java.io.FileReader; import java.io.IOException; 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); } }HELLO FROM DOT NET PERLSLine count: 3
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.
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.