java

Java Program to Count the Number of Lines in a File

In this tutorial, we are going to see how to write a Java program to count the number of lines in a file using BufferedReader to read the contents of the file.
 

Program to Count the Number of Lines in a File
import java.io.*;

public class Main 
{
   public static void main(String[] args) throws IOException 
   {
      // The input file
      File file = new File("myFile.txt"); 
      // Initialize the counter to zero
      int nbrOfLine = 0;            
      // Create the File Reader object
      FileReader fr = new FileReader(file);
      // Create the BufferedReader object
      BufferedReader br = new BufferedReader(fr);  
      String str;
      // Read the contents of the file
      while((str = br.readLine()) != null)
      {
         //For each line, increment the number of lines
         nbrOfLine++;               
            
      }
      fr.close();
      System.out.println("Number of lines in the file is: "+ nbrOfLine); 
   }
}

Output:

Number of lines in the file is: 15
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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