Sometimes you just want to count the number of lines in a file, rather than reading the content of file. The easiest way, I feel, is to use LineNumberReader for counting the lines in a file in Java.
LineNumberReader class has a method getLineNumber() that gives the current line number of the file. So the logic for counting the number of lines in a file is as follows-
Using the LineNumberReader read all the lines of the files until you reach the end of file. Then use getLineNumber() method to get the current line number.
Using the getLineNumber() method you can also display line numbers along with the lines of the file.
Java program to count number of lines in a file
If you have a file with lines as follows-
This is a test file. Line number reader is used to read this file. This program will read all the lines. It will give the count.
Then you can get the count of lines using the following code-
import java.io.File; import java.io.FileReader; import java.io.IOException; import java.io.LineNumberReader; public class LineNumberDemo { public static void main(String[] args) { LineNumberReader reader = null; try { reader = new LineNumberReader(new FileReader(new File("F:\\abc.txt"))); // Read file till the end while ((reader.readLine()) != null); System.out.println("Count of lines - " + reader.getLineNumber()); } catch (Exception ex) { ex.printStackTrace(); } finally { if(reader != null){ try { reader.close(); } catch (IOException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } } }
Output
Count of lines – 4
That's all for this topic How to Count Lines in a File in Java. If you have any doubt or any suggestions to make please drop a comment. Thanks!
>>>Return to Java Programs Page
Related Topics
You may also like-