计算txt文件中的行数java文件io
问题描述:
while (inputStream.hasNextLine()){
System.out.println(count);
count = count + 1 ;
}
例如,我的文本文件有1000行,每行都有关于它的信息。它似乎在计算所有的数字而不是每一行。计算txt文件中的行数java文件io
答
假设inputStream
是你需要从InputStream
while (inputStream.hasNextLine()) {
inputStream.nextLine(); <-- add this
...
答
你的循环消耗的数据Scanner
永远不会结束,因为你不消费流。使用Java 8的替代方案:
try (Stream<String> s = Files.lines(Paths.get(file), UTF_8)) {
count = s.count();
}