问题
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