Tuesday, June 13, 2023

How to Count Lines in a File in Java

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

  1. Java Program to Print Line Numbers With Lines in Java
  2. Reading Delimited File in Java Using Scanner
  3. Reading File in Java Using Files.lines And Files.newBufferedReader
  4. How to Read File From The Last Line in Java
  5. Zipping Files And Folders in Java

You may also like-

  1. How to Create Password Protected Zip File in Java
  2. Print Odd-Even Numbers Using Threads And wait-notify Java Program
  3. Convert double to int in Java
  4. Java Program to Get All The Tables in a DB Schema
  5. Java Abstract Class and Abstract Method
  6. Java Collections Interview Questions And Answers
  7. Java Stream API Tutorial
  8. Interface Static Methods in Java