Exercise:
Write a Java Program to count number of lines present in the file.
1.count using Scanner class
Click Here to View the Solution!
import java.io.File;
import java.util.Scanner;
public 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();
}
}
}
Click Here to View the Output!
First Line
Second Line
Third Line
Click Here to View the Explanation!
- This program is used to find the number of lines in a file by using an object of the class
java.util.Scanner
. - Initially, an integer variable
count
is initialized ascount = 0
and atry catch block
, that will hold thescanner
object. - A
File
object file is created that will take the fileinput.txt
as a parameter. - Then a
Scanner
object is created that will take thisFile
object as a parameter. - A
while loop
is then initialized that will usesc.hasNextLine()
method of the Scanner class to loop through the lines of the file input.txt until it is true. - The
sc.nextLine()
method will access all the lines in the file and each time an increment of one occurs in thecount
variable. - The loop will end when
sc.hasNextLine()
becomes false. - In the end, the final value of the variable count will be printed depicting the number of lines in
input.txt
.
2.count using java.nio.file package
Click Here to View the Solution!
import java.nio.file.*;
public 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();
}
}
}
Click Here to View the Output!
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.
Click Here to View the Explanation!
- This program is used to find the number of lines in a file by using the
package
java.nio.file
. - In the
try catch block
, a connection is established with the file through thePaths.get()
method. - A
lines()
method is used to read all the lines in a file by taking the file object as input. And at the same time, counting the number of these lines using thecount()
method and storing the output in a long type variable count. The expression is as follows:long count = Files.lines(file).count()
- Finally, the value in count is printed which will give the total number of lines in the
input.txt
.