Write a Java Program to Count number of lines present in the file

As a Java programmer, one of the common tasks you might come across is to count the number of lines present in a file.

This task might seem trivial, but it can be quite useful in a variety of scenarios.

In this tutorial, we will walk you through the steps to write a Java program that counts the number of lines present in a file.


Import necessary packages

To begin with, we need to import the necessary packages.

In this case, we need to import the java.io package as we will be working with files.

import java.io.*;

Open the file

Next, we need to open the file that we want to count the lines for.

We can use the BufferedReader class to read the file line by line.

BufferedReader reader = new BufferedReader(new FileReader("file.txt"));

Read the file line by line

Once we have opened the file, we can read it line by line using the readLine() method of the BufferedReader class.

We can use a while loop to iterate over each line of the file.

int count = 0;
while (reader.readLine() != null) {
    count++;
}

Close the file

After we have read the file, we should close it to free up system resources.

reader.close();

Finally, we can print the number of lines present in the file.

System.out.println("Number of lines in the file: " + count);

Putting it all together, our Java program to count the number of lines present in a file looks like this:

import java.io.*;

public class LineCounter {
    public static void main(String[] args) throws IOException {
        BufferedReader reader = new BufferedReader(new FileReader("file.txt"));
        int count = 0;
        while (reader.readLine() != null) {
            count++;
        }
        reader.close();
        System.out.println("Number of lines in the file: " + count);
    }
}

In conclusion, counting the number of lines present in a file is a common task in Java programming, and it can be accomplished using the BufferedReader class.

By following the above steps, you can easily write a Java program that counts the number of lines present in a file.