Java でファイルの行数を取得する
Farkhanda Athar
2023年10月12日
Java
Java File

この記事では、ファイルの合計行数をカウントするさまざまな方法について説明します。
ファイルの行をカウントする手順は、次の 4つのステップで構成されます。
- ファイルを開きます。
- 行ごとに読み取り、各行の後にカウントを 1つずつインクリメントします。
- ファイルを閉じます。
- カウントを読みます。
ここでは、2つのメソッドを使用して、ファイル内の行の数をカウントしました。これらのメソッドは、Java File
クラスと Scanner
クラスです。
Java の Scanner
クラスを使用してファイルの行数を数える
このアプローチでは、Scanner
クラスの nextLine()
メソッドが使用され、ファイルの各行にアクセスします。行数は、input.txt
ファイルの行数によって異なります。プログラムはファイルの内容も出力します。
コード例:
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 sc = new Scanner(file);
while (sc.hasNextLine()) {
sc.nextLine();
count++;
}
System.out.println("Total Number of Lines: " + count);
sc.close();
} catch (Exception e) {
e.getStackTrace();
}
}
}
以下に示すように、ファイルが 3 行で構成されている場合。
This is the first line.This is the second line.This is the third line.
次に、出力は次のようになります
出力:
Total Number of Lines: 3
java.nio.file
パッケージを使用してファイルの行数を数える
この目的のために、lines()
メソッドはファイルのすべての行をストリームとして読み取り、count()
メソッドはストリーム内の要素の数を返します。
コード例:
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("Total Lines: " + count);
} catch (Exception e) {
e.getStackTrace();
}
}
}
出力:
Total Lines: 3
チュートリアルを楽しんでいますか? <a href="https://www.youtube.com/@delftstack/?sub_confirmation=1" style="color: #a94442; font-weight: bold; text-decoration: underline;">DelftStackをチャンネル登録</a> して、高品質な動画ガイドをさらに制作するためのサポートをお願いします。 Subscribe