使用 Java 的 Scanner 类确定文件结尾

发布于 2024-10-03 04:41:15 字数 218 浏览 0 评论 0原文

我正在尝试从文本文件中读取文本。我需要帮助确定文件何时结束。在 Java 中如何确定这一点?

FileInputStream istream = new FileInputStream("\""+filename+"\"");      
Scanner input = new Scanner(istream);
while(EOF != true)
{
 ....
}

I am trying to read text from a text file. I need help figuring out when the end of file has occurred. How can I determine this in Java?

FileInputStream istream = new FileInputStream("\""+filename+"\"");      
Scanner input = new Scanner(istream);
while(EOF != true)
{
 ....
}

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(2

长不大的小祸害 2024-10-10 04:41:15

您可以使用hasNextLine()进行检查:

Scanner input = new Scanner(new File("\""+filename+"\""));
while(input.hasNextLine())
{
   String data = input.nextLine();
}

You can check using hasNextLine():

Scanner input = new Scanner(new File("\""+filename+"\""));
while(input.hasNextLine())
{
   String data = input.nextLine();
}
眼睛会笑 2024-10-10 04:41:15

基于行的检索可能是您想要的,但基于标记也很有用。
您可以在 Scanner

public boolean hasNext()

如果此扫描器的输入中有另一个令牌,则返回true。此方法可能会在等待输入扫描时阻塞。 扫描仪不会前进超过任何输入。

指定者:
接口 Iterator

中的 hasNext

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

抛出:
IllegalStateException - 如果此 Scanner 已关闭

另请参阅:
迭代器

Line based retrieval may be what you want, but token based can also be useful.
You can see in documentation of Scanner

public boolean hasNext()

Returns true if this Scanner has another token in its input. This method may block while waiting for input to scan. The Scanner does not advance past any input.

Specified by:
hasNext in interface Iterator<String>

Returns:
true if and only if this Scanner has another token

Throws:
IllegalStateException - if this Scanner is closed

See Also:
Iterator

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文