Java 如何确定何时到达文件末尾?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/4208502/
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
How to determine when end of file has been reached?
提问by Blackbinary
I am trying to read text from a text file. I need help figuring out when the end of file has occured. How can I determine this in Java?
我正在尝试从文本文件中读取文本。我需要帮助弄清楚文件何时结束。我如何在 Java 中确定这一点?
FileInputStream istream = new FileInputStream("\""+filename+"\"");
Scanner input = new Scanner(istream);
while(EOF != true)
{
....
}
Thanks!
谢谢!
回答by jjnguy
You can check using hasNextLine()
:
您可以使用hasNextLine()
以下方法检查:
Scanner input = new Scanner(new File("\""+filename+"\""));
while(input.hasNextLine())
{
String data = input.nextLine();
}
回答by Thomas Langston
Line based retrieval may be what you want, but token based can also be useful.
You can see in documentation of Scanner
基于行的检索可能是您想要的,但基于令牌的检索也很有用。你可以在文档中看到Scanner
public boolean hasNext()
Returns
true
if thisScanner
has another token in its input. This method may block while waiting for input to scan. TheScanner
does not advance past any input.Specified by:
hasNext
in interfaceIterator<String>
Returns:
true
if and only if thisScanner
has another tokenThrows:
IllegalStateException
- if thisScanner
is closedSee Also:
Iterator
返回它的输入中
true
是否Scanner
有另一个标记。此方法可能会在等待输入扫描时阻塞。在Scanner
不执行任何输入。指定者:
hasNext
在接口中Iterator<String>
返回:
true
当且仅当它Scanner
有另一个令牌抛出:
IllegalStateException
- 如果这Scanner
是关闭的也可以看看:
Iterator