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

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-14 14:34:06  来源:igfitidea点击:

How to determine when end of file has been reached?

javafilefile-iojava.util.scanner

提问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 trueif this Scannerhas another token in its input. This method may block while waiting for input to scan. The Scannerdoes not advance past any input.

Specified by: hasNextin interface Iterator<String>

Returns: trueif and only if this Scannerhas another token

Throws: IllegalStateException- if this Scanneris closed

See Also: Iterator

返回它的输入中true是否Scanner有另一个标记。此方法可能会在等待输入扫描时阻塞。在Scanner不执行任何输入。

指定者: hasNext在接口中Iterator<String>

返回: true当且仅当它Scanner有另一个令牌

抛出: IllegalStateException- 如果这Scanner是关闭的

也可以看看: Iterator