Home
Java
Line Count for File
Updated Dec 21, 2022
Dot Net Perls
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 pages with code examples, which are updated to stay current. Programming is an art, and it can be learned from examples.
Donate to this site to help offset the costs of running the server. Sites like this will cease to exist if there is no financial support for them.
Sam Allen is passionate about computer languages, and he maintains 100% of the material available on this website. He hopes it makes the world a nicer place.
This page was last updated on Dec 21, 2022 (edit link).
Home
Changes
© 2007-2025 Sam Allen