Javaでファイルの行数をカウントする方法をメモしておきます。
環境
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
- Java 8 |
ファイルの行数をカウントする方法
Java8から利用できるFiles.linesを使ってやればOKです。デフォルトだとファイルの文字コードはUTF-8
として扱います。
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// ファイルパス | |
Path path = Paths.get("/path/to/file"); | |
// ファイルの行数 | |
long lineCount = Files.lines(path).count(); | |
// ファイルの行数(文字コードをSJISに指定する場合) | |
long lineCount = Files.lines(path, Charset.forName("SJIS")).count(); |
まとめ
ファイルの行数をカウントする方法でした。