Home
Map
Line Count for FileUse the BufferedReader class and readLine to count lines in a text file.
Java
This page was last reviewed on Dec 21, 2022.
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).
File
Our example. This program might throw an IOException, so it has the "throws IOException" notation at its top. It includes classes from the java.io namespace.
Detail This method returns null when no more lines exist in the file (at end-of-file). We call it repeatedly.
Detail 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.
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 PERLS
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.
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.
Dot Net Perls is a collection of tested code examples. Pages are continually updated to stay current, with code correctness a top priority.
Sam Allen is passionate about computer languages. In the past, his work has been recommended by Apple and Microsoft and he has studied computers at a selective university in the United States.
This page was last updated on Dec 21, 2022 (edit link).
Home
Changes
© 2007-2024 Sam Allen.