Java 程序:计算文件中包含的行数

要理解此示例,您应了解以下Java编程主题


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

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.nio.file 包计算文件行数的Java程序

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


另请阅读

你觉得这篇文章有帮助吗?

我们的高级学习平台,凭借十多年的经验和数千条反馈创建。

以前所未有的方式学习和提高您的编程技能。

试用 Programiz PRO
  • 交互式课程
  • 证书
  • AI 帮助
  • 2000+ 挑战