How to Get the Count of Line of a File in Java

Farkhanda Athar Feb 02, 2024
  1. Count the Number of Lines in File Using the Scanner Class in Java
  2. Count the Number of Lines in File Using the java.nio.file Package
How to Get the Count of Line of a File in Java

The article will explain the various methods to count the total number of lines in a file.

The procedure of counting the lines in a file consists of four steps.

  1. Open the file.
  2. Read line by line and increment count by one after each line.
  3. Close the file.
  4. Read the count.

Here we have used two methods to count the number of lines in a file. These methods are Java File Class and Java Scanner Class.

Count the Number of Lines in File Using the Scanner Class in Java

In this approach, the nextLine() method of the Scanner class is used, which accesses each line of the file. The number of lines depends upon the lines in the input.txt file. The program also prints the file content.

Example codes:

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

class Main {
  public static void main(String[] args) {
    int count = 0;

    try {
      File file = new File("input.txt");

      Scanner sc = new Scanner(file);

      while (sc.hasNextLine()) {
        sc.nextLine();
        count++;
      }
      System.out.println("Total Number of Lines: " + count);

      sc.close();
    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

If the file consists of three lines, as shown below.

This is the first line.This is the second line.This is the third line.

Then the output will be

Output:

Total Number of Lines: 3

Count the Number of Lines in File Using the java.nio.file Package

For this purpose, the lines() method will read all lines of a file as a stream, and the count() method will return the number of elements in a stream.

Example Codes:

import java.nio.file.*;

class Main {
  public static void main(String[] args) {
    try {
      Path file = Paths.get("input.txt");

      long count = Files.lines(file).count();
      System.out.println("Total Lines: " + count);

    } catch (Exception e) {
      e.getStackTrace();
    }
  }
}

Output:

Total Lines: 3

Related Article - Java File