How to Get the Count of Line of a File in Java
-
Count the Number of Lines in File Using the
Scanner
Class in Java -
Count the Number of Lines in File Using the
java.nio.file
Package
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.
- Open the file.
- Read line by line and increment count by one after each line.
- Close the file.
- 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