示例 1: Java 程序使用 Scanner 类计算文件中的行数
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(); } } }
在上面的例子中,我们使用了
Scanner
类的
nextLine()
方法来访问文件的每一行。在这里,根据文件 input.txt 文件包含的行数,程序显示输出。
在这种情况下,我们有一个文件名input.txt,内容如下
First Line Second Line Third Line
所以,我们会得到输出
Total Number of Lines: 3
示例 2: Java 程序使用 java.nio.file 包计算文件中的行数
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(); } } }
在上面的例子中,
lines()-将文件的所有行作为流读取
count()-返回流中元素的数量
这里,如果文件input.txt包含以下内容:
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.
程序将打印总行数: 3。