Number of Lines in File

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

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 Reply

Your email address will not be published. Required fields are marked *