Unlocking the Secrets of File Handling in Java

Counting Lines in a File: Two Approaches

Understanding how to count the number of lines in a file is a fundamental skill in Java, essential for any project. In this article, we’ll explore two methods to achieve this.

Method 1: Using the Scanner Class

One popular approach to counting lines in a file is by utilizing the Scanner class. By leveraging the nextLine() method, we can access each line of the file and keep track of the total count.


import java.io.File;
import java.io.FileNotFoundException;
import java.util.Scanner;

public class LineCounter {
    public static void main(String[] args) {
        File file = new File("input.txt");
        try (Scanner scanner = new Scanner(file)) {
            int lineNumber = 0;
            while (scanner.hasNextLine()) {
                scanner.nextLine();
                lineNumber++;
            }
            System.out.println("Total Lines: " + lineNumber);
        } catch (FileNotFoundException e) {
            System.out.println("File not found");
        }
    }
}

Suppose we have a file named input.txt containing the following content:


Line 1
Line 2
Line 3

By running our Java program, we’ll get an output indicating the total number of lines in the file.

Method 2: Using java.nio.file

Another way to count lines in a file is by harnessing the capabilities of the java.nio.file package. Specifically, we can use the lines() method to read all lines of the file as a stream, and then employ the count() method to return the number of elements in that stream.


import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.Paths;

public class LineCounter {
    public static void main(String[] args) {
        try {
            long lines = Files.lines(Paths.get("input.txt")).count();
            System.out.println("Total Lines: " + lines);
        } catch (IOException e) {
            System.out.println("Error reading file");
        }
    }
}

Let’s revisit our input.txt file, this time with the following content:


Line 1
Line 2
Line 3

When we run our Java program, it will print Total Lines: 3.

Taking it to the Next Level

Now that we’ve explored two ways to count lines in a file, it’s essential to consider other aspects of file handling in Java. For instance, have you ever wondered how to read the content of a file line by line?

Mastering these fundamental skills will equip you to tackle even the most complex Java projects.

Further Exploration

Want to dive deeper into the world of Java file handling? Check out our article on reading file content line by line to unlock even more possibilities.

Leave a Reply