2015-02-24 38 views
0
while (inputStream.hasNextLine()){ 
    System.out.println(count); 
    count = count + 1 ; 
} 

例如,我的文本文件有1000行,每行都有关于它的信息。它似乎在计算所有的数字而不是每一行。计算txt文件中的行数java文件io

回答

3

假设inputStream是你需要从InputStream

while (inputStream.hasNextLine()) { 
    inputStream.nextLine(); <-- add this 
    ... 
1

你的循环消耗的数据Scanner永远不会结束,因为你不消费流。使用Java 8的替代方案:

try (Stream<String> s = Files.lines(Paths.get(file), UTF_8)) { 
    count = s.count(); 
}