Number of Lines in File


Sometimes, in coding, it is required to know the number of lines existing in a file programmatically. There is no direct way (a predefined method) to find out in Java. To do the job, the help of BufferedReader's readLine() method is taken. While reading each line, the counter is incremented; the simplest way to achieve the task. Another style of knowing the number of lines is using LineNumberInputStream and LineNumberReader. But these classes are popular to add line numbers in a destination file that do not exist in source file. Indirectly, adding line numbers help us to know the number of lines.

Example on Number of Lines in File
import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

public class CountLines
{
  public static void main(String args[]) throws IOException
  {
    BufferedReader br = new BufferedReader(new FileReader("pqr.txt"));
    int counter = 0;
    String str;
    while( (str = br.readLine()) != null)
    {
      counter++;
    }
    br.close();
    System.out.println("No. of line in the file: " + counter);
   }
}

BufferedReader br = new BufferedReader(new FileReader(“pqr.txt”));

"pqr.txt" is the file to know the number of lines existing and is passed to FileReader constructor. The above statement is a concise form where anonymous object of FileReader is used. This statement can be split into two for a better understanding.

FileReader fr = new FileReader(“pqr.txt”);
BufferedReader br = new BufferedReader(fr);

When a FileReader object fr is created, it is necessary to close with fr.close().

In place of BufferedReader, DataInputStream can be used to count the number of lines.

Leave a Comment

Your email address will not be published.