Popular Tutorials
Start Learning JavaCertification Courses
Created with over a decade of experience and thousands of feedback.
Java Program to Count number of lines present in the file
In this example, we will learn to count the number of lines present in a file in Java.
To understand this example, you should have the knowledge of the following Java programming topics:
Example 1: Java program to count the number of lines in a file using Scanner class
import java.io.File;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int count = 0;
try {
// create a new file object
File file = new File("input.txt");
// create an object of Scanner
// associated with the file
Scanner sc = new Scanner(file);
// read each line and
// count number of lines
while(sc.hasNextLine()) {
sc.nextLine();
count++;
}
System.out.println("Total Number of Lines: " + count);
// close scanner
sc.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
In the above example, we have used the nextLine() method of the Scanner class to access each line of the file. Here, depending on the number of lines the file input.txt file contains, the program shows the output.
In this case, we have a file name input.txt with the following content
First Line
Second Line
Third Line
So, we will get output
Total Number of Lines: 3
Example 2: Java program to count the number of lines in a file using java.nio.file package
import java.nio.file.*;
class Main {
public static void main(String[] args) {
try {
// make a connection to the file
Path file = Paths.get("input.txt");
// read all lines of the file
long count = Files.lines(file).count();
System.out.println("Total Lines: " + count);
} catch (Exception e) {
e.getStackTrace();
}
}
}
In the above example,
- lines() - read all lines of the file as a stream
- count() - returns the number of elements in the stream
Here, if the file input.txt contains the following content:
This is the article on Java Examples.
The examples count number of lines in a file.
Here, we have used the java.nio.file package.
The program will print Total Lines: 3.
Also Read:
Did you find this article helpful?