在此示例中,我們將學習計算Java文件中存在的行數(shù)。
import java.io.File;
import java.util.Scanner;
class Main {
public static void main(String[] args) {
int count = 0;
try {
//創(chuàng)建一個新的文件對象
File file = new File("input.txt");
//創(chuàng)建一個Scanner對象
//與文件關聯(lián)
Scanner sc = new Scanner(file);
//讀每一行,然后
//計算行數(shù)
while(sc.hasNextLine()) {
sc.nextLine();
count++;
}
System.out.println("總行數(shù): " + count);
// 關閉掃描器
sc.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}在上面的示例中,我們使用了掃描器Scanner類的nextLine()方法來訪問文件的每一行。在這里,根據(jù)文件input.txt文件包含的行數(shù),該程序?qū)@示輸出。
在這種情況下,我們文件名為 input.txt 具有以下內(nèi)容:
First Line Second Line Third Line
因此,我們將獲得輸出
總行數(shù): 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("總行數(shù): " + count);
} catch (Exception e) {
e.getStackTrace();
}
}
}在上面的示例中,
lines() - 以流的形式讀取文件的所有行
count() - 返回流中元素的數(shù)量
在這里,如果文件input.txt包含以下內(nèi)容:
這是一篇關于Java示例的文章。 這些示例計算文件中的行數(shù)。 在這里,我們使用了java.nio.file包。
程序?qū)⒋蛴?strong>總行數(shù):3。