What's the difference between (reader.ready()) and using a for loop to read through a file? [closed]

余生颓废 提交于 2019-12-14 03:00:47

问题


In my previous question, I asked about a problem with looping through a file, and solved it. However, I realised that the method failed to read the last set of lines/record. So I changed the original for loop to a while(reader.ready()). So:

Original for loop:

     int numberOfLines = readLines();
     numberOfLines = numberOfLines / 6;

     for(int i=0;i < numberOfLines; i++)

Changed that to:

BufferedReader reader = new BufferedReader(new FileReader("test.dat"));

while(reader.ready())

What's the difference between the two, and a little more specifically, what exactly does the .ready() do?


回答1:


From the Javadoc:

Tells whether this stream is ready to be read. A buffered character stream is ready if the buffer is not empty, or if the underlying character stream is ready.

Returns:
True if the next read() is guaranteed not to block for input, false otherwise. Note that returning false does not guarantee that the next read will block.

So, the buffer will be ready if read is guaranteed not to block.

As JB Nizet points out, this does not necessarily mean that you have reached the end of the file. If, for any reason, your stream might block, then ready will return false.

Instead, try reading your files like this:

String line = reader.readLine();
while (line != null) {
    // code code code
    line = reader.readLine();
}


来源:https://stackoverflow.com/questions/15325652/whats-the-difference-between-reader-ready-and-using-a-for-loop-to-read-thro

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!