Java扫描仪计算文件中的行数
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/18902706/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Java scanner count lines in file
提问by Justas S
I have a question, I tried to create an app that counts all occurences of a symbol in a file... The scanner method "nextLine" stops at an empty line... Is there a way to keep it going until it reaches the real end of the file?
我有一个问题,我试图创建一个应用程序来计算文件中符号的所有出现次数……扫描仪方法“nextLine”在空行处停止……有没有办法让它继续运行,直到它到达真正的文件结束?
In short: can I get the REAL number of lines in a file?
简而言之:我可以获得文件中的真实行数吗?
Thankyou in advance!
先感谢您!
回答by Eugen Halca
You can use a loop:
您可以使用循环:
int count = 0;
while (scanner.hasNextLine()) {
count++;
scanner.nextLine();
}
count
will contain number of lines.
count
将包含行数。
回答by dajavax
See Scanner.hasNextLine(), you should probably use that in the loop condition. There is also a Scanner.hasNext()if it works better for your needs.
请参阅Scanner.hasNextLine(),您可能应该在循环条件中使用它。如果它更适合您的需要,还有一个Scanner.hasNext()。
回答by wolf123450
So I've been doing some research about this problem. I've been coming up against it recently while writing a line counting program in Java for the class I'm taking.
所以我一直在研究这个问题。我最近在为我正在上的课程用 Java 编写行计数程序时遇到了它。
The reason the scannerclass does this is because scanner.next() and scanner.nextLine() return tokens, which are separated by delimiters. By default the delimiter is whitespace. So what's happening is that when you call scanner.hasNext() or scanner.hasNextLine() is that it looks to see if there is a token after the next delimiter. When a file ends in a newline character, there is no token after that, so hasNext() and hasNextLine() return false.
扫描器类这样做的原因是因为scanner.next() 和scanner.nextLine() 返回由分隔符分隔的标记。默认情况下,分隔符是whitespace。所以发生的事情是,当你调用scanner.hasNext() 或scanner.hasNextLine() 时,它会查看下一个分隔符之后是否有标记。当文件以换行符结尾时,之后没有标记,因此 hasNext() 和 hasNextLine() 返回 false。
As far as I can tell, to do what you want you'd need to count the number of delimiters, which is better handled in Martinus's answer. See also AFinkelstein's answer.
据我所知,要执行您想要的操作,您需要计算分隔符的数量,这在 Martinus's answer 中处理得更好。另请参阅 Afinkelstein 的回答。