English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
In this example, we will learn to calculate the number of lines existing in a Java file.
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 a Scanner object //Associate with the file Scanner sc = new Scanner(file); //Read each line, then //Count the number of lines while(sc.hasNextLine()) { sc.nextLine(); count++; } count); + catch (Exception e) { // Close the scanner sc.close(); } e.getStackTrace(); } } }
In the above example, we used the nextLine() method of the Scanner class to access each line of the file. Here, according to the number of lines in the file input.txt, the program will display the output.
In this case, our file name is input.txt and it contains the following content:
First Line Second Line Third Line
Therefore, we will get the output
Total lines: 3
import java.nio.file.*; class Main { public static void main(String[] args) { try { //Establish a connection with the file Path file = Paths.get("input.txt"); //Read all lines of the file long count = Files.lines(file).count(); count); + catch (Exception e) { } e.getStackTrace(); } } }
In the above example,
lines() - Read all lines of the file in stream form
count() - Return the number of elements in the stream
Here, if the file input.txt contains the following content:
This is an article about Java examples. These examples calculate the number of lines in the file. Here, we use the java.nio.file package.
The program will printTotal Number of Lines:3.