计算文件中内容的行数的 Java 程序

要理解此示例,您应该具备以下 Java 编程的知识:

示例 1:Java 程序使用 Scanner 类计算文件中的行数

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();
    }
  }
}

在上面的例子中,我们使用了 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.*;

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();
    }
  }
}

在上面的例子中,

  • 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.

该程序将打印:

Total Lines: 3