java BufferedReader 在while循环中准备好方法来确定EOF?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4543725/
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-10-30 06:52:13  来源:igfitidea点击:

BufferedReader ready method in a while loop to determine EOF?

javabufferedreader

提问by BobTurbo

I have a large file (English Wikipedia articles only database as XML files). I am reading one character at a time using BufferedReader. The pseudocode is:

我有一个大文件(英文维基百科文章仅作为 XML 文件的数据库)。我正在使用BufferedReader. 伪代码是:

file = BufferedReader...

while (file.ready())
    character = file.read()

Is this actually valid? Or will readyjust return falsewhen it is waiting for the HDD to return data and not actually when the EOFhas been reached? I tried to use if (file.read() == -1)but seemed to run into an infinite loop that I literally could not find.

这实际上有效吗?或者ready只是false在等待 HDD 返回数据时返回,而不是在实际EOF到达时返回?我尝试使用,if (file.read() == -1)但似乎遇到了一个我确实找不到的无限循环。

I am just wondering if it is reading the whole file as my statistics say 444,380 Wikipedia pages have been read but I thought there were many more articles.

我只是想知道它是否正在阅读整个文件,因为我的统计数据显示已经阅读了 444,380 个维基百科页面,但我认为还有更多的文章。

采纳答案by Mike Samuel

This is not guaranteed to read the whole input. ready()just tells you if the underlying stream has some content ready. If it is abstracting over a network socket or file, for example, it could mean that there isn't any buffered data available yet.

这不能保证读取整个输入。 ready()只是告诉你底层流是否准备好了一些内容。如果抽象通过网络接口或文件,例如,这可能意味着,没有任何的缓冲数据还没有

回答by Stephen C

The Reader.ready()method is not intended to be used to test for end of file. Rather, it is a way to test whether calling read()will block.

Reader.ready()方法不打算用于测试文件结尾。相反,它是一种测试调用是否read()会阻塞的方法。

The correct way to detect that you have reached EOF is to examine the result of a readcall.

检测您是否已到达 EOF 的正确方法是检查read调用的结果。

For example, if you are reading a character at a time, the read()method returns an intwhich will either be a valid character or -1if you've reached the end-of-file. Thus, your code should look like this:

例如,如果您一次读取一个字符,该read()方法将返回int一个有效字符或-1您已到达文件末尾的 。因此,您的代码应如下所示:

int character;
while ((character = file.read()) != -1) {
    ...
}