How to Count line numbers in a .txt file in Java

Counting the number of lines in a .txt file is a common task that can be easily accomplished in Java. This tutorial will walk you through the process step-by-step.

Prerequisites

Before we start, ensure you have the following installed:

  • JDK (Java Development Kit)
  • An IDE (Integrated Development Environment) like IntelliJ IDEA, Eclipse, or simply a text editor and command line.

Step 1: Setting Up Your Project

  1. Create a new Java project: If you’re using an IDE, create a new project. If you’re using a text editor, create a new directory for your project.
  2. Create a new Java class: Inside your project, create a new Java file, say ‘LineCounter.java’.

Step 2: Import Necessary Packages

In your ‘LineCounter.java’ file, start by importing the necessary classes:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;

Step 3: Create the Main Class and Method

Define the main class and the main method:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: java LineCounter <file-path>");
            return;
        }
        
        String filePath = args[0];
        int lineCount = countLines(filePath);
        
        if (lineCount != -1) {
            System.out.println("Number of lines in the file: " + lineCount);
        } else {
            System.out.println("An error occurred while counting the lines.");
        }
    }
}

Step 4: Implement the ‘countLines’ Method

Now, implement the ‘countLines’ method that reads the file and counts the lines:

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
public class LineCounter {
    public static void main(String[] args) {
        if (args.length != 1) {
            System.out.println("Usage: java LineCounter <file-path>");
            return;
        }
        
        String filePath = args[0];
        int lineCount = countLines(filePath);
        
        if (lineCount != -1) {
            System.out.println("Number of lines in the file: " + lineCount);
        } else {
            System.out.println("An error occurred while counting the lines.");
        }
    }
    public static int countLines(String filePath) {
    int lineCount = 0;
    
    try (BufferedReader reader = new BufferedReader(new FileReader(filePath))) {
        while (reader.readLine() != null) {
            lineCount++;
        }
    }
    catch (IOException e) {
        e.printStackTrace();
        return -1;
    }
    
    return lineCount;
   }

}

Step 5: Explanation

  1. Main Method:
    • The ‘main’ method checks if a file path is provided as an argument.
    • It then calls the ‘countLines’ method with the file path and prints the number of lines.
  2. countLines Method:
    • Uses a ‘BufferedReader’ wrapped around a ‘FileReader’ to read the file line by line.
    • For each line read, it increments the ‘lineCount’ variable.
    • If an ‘IOException’ occurs, it prints the stack trace and returns ‘-1’ to indicate an error.

Step 6: Running the Program

  1. Compile the program:
    javac LineCounter.java
    
  2. Run the program:
    java LineCounter path/to/your/file.txt

Replace ‘path/to/your/file.txt’ with the actual path to the ‘.txt’ file you want to count the lines of.

Example

Suppose you have a file named ‘example.txt’ with the following content:

Hello, world!
This is a test file.
Welcome to CodeSpeedy.

Running the program as follows:

java LineCounter example.txt

output:

Number of lines in the file: 3

Conclusion

You have successfully written a Java program to count the number of lines in a ‘.txt’ file. This tutorial covers file reading, exception handling, and basic command-line operations in Java.

“HAPPY CODING”

Leave a Comment

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

Scroll to Top