Count the Number of Lines in a Text File in Java

Hello Learners, today we are going to learn how to count the number of lines in a text file using Java. You just have to know about the basic idea of Java file handling and there you go.

Counting the Lines of a File: Basic idea

  • FileReader Class: This class is used to read the data from a file and returns it in byte format.
  • BufferedReader: The class is used to read text from the input stream.
  • readLine() method: This method belongs to BufferedReader class. It is used to read a single line from a file and that’s what we exactly need here.

we are going to use the above two classes in our code and the readLine method that makes it easy for us. So, here we have a sample file containing three lines. See the File below: sample.txt 

Greeting from CodeSpeedy!
Today you will learn how to count the number of lines in a text file.
you are reading this Article by Avantika Singh.
import java.io.*;

public class linesInFile {	
     public static void main(String[] arg) throws IOException   {

      File f=new File("C:\\Users\\lenovo\\Documents\\sample.txt"); 
      int lines=0;    
      FileReader fr=new FileReader(f); 
      BufferedReader br = new BufferedReader(fr);            
      while(br.readLine()!=null) 
      {
         lines++;       
      }
      fr.close();
      System.out.println("no. of lines in the file: "+lines);
   }
}

OUTPUT:

no. of lines in the file: 3
Explanation:

The code is very simple to understand. Follow the below steps:

  • At first, you create a file object providing the path of the file you want to.
  • In the next step, you create an object of BufferedReader class to read the input from the file.
  • Declare and initialize a variable as zero for holding the number of lines.
  • Call the readLine method on BUfferedReader object over a file loop.
  • check for the condition until there isn’t remaining a single file in the file and in increment the line variable.
  • after the loop ends, do not forget to close the file and print the number of lines.

That’s it, Done. Try do it on your own, it’s a simple code. Click on the link to learn more about Java File Handling. So, that’s all for now about how to count the number of lines in a text file using Java.

Leave a Reply

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