在此示例中,我们将学习计算Java文件中存在的行数。
import java.io.File;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int count = 0;
try {
//创建一个新的文件对象
File file = new File("input.txt");
//创建一个Scanner对象
//与文件关联
Scanner sc = new Scanner(file);
//读每一行,然后
//计算行数
while(sc.hasNextLine()) {
sc.nextLine();
count++;
}
System.out.println("总行数: " + count);
// 关闭扫描器
sc.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}在上面的示例中,我们使用了扫描器Scanner类的nextLine()方法来访问文件的每一行。在这里,根据文件input.txt文件包含的行数,该程序将显示输出。
在这种情况下,我们文件名为 input.txt 具有以下内容:
First Line Second Line Third Line
因此,我们将获得输出
总行数: 3
import java.nio.file.*;
class Main {
public static void main(String[] args) {
try {
//与文件建立连接
Path file = Paths.get("input.txt");
//读取文件的所有行
long count = Files.lines(file).count();
System.out.println("总行数: " + count);
} catch (Exception e) {
e.getStackTrace();
}
}
}在上面的示例中,
lines() - 以流的形式读取文件的所有行
count() - 返回流中元素的数量
在这里,如果文件input.txt包含以下内容:
这是一篇关于Java示例的文章。 这些示例计算文件中的行数。 在这里,我们使用了java.nio.file包。
程序将打印总行数:3。