When reading stream, why not stop iterating when 0 bytes read

The standard idiom when reading from a stream is to check for EOF (-1):

while((bytesRead = inputStream.read(buffer)) != -1)

This seems pretty standard - I checked source for popular libraries like Apache Commons and it seems to be the defacto standard.

Why do we not stop at 0 as well? Wouldn't > -1 be better? Why do whatever work is in the loop when we didn't read anything?

Jon Skeet
people
quotationmark

Basically because it would be pointless. Look at the documentation:

If the length of b is zero, then no bytes are read and 0 is returned; otherwise, there is an attempt to read at least one byte. If no byte is available because the stream is at the end of the file, the value -1 is returned; otherwise, at least one byte is read and stored into b.

So unless you're passing in an empty buffer (which is basically a bug in pretty much all cases; I personally wish the method would throw an exception in that case) the return value will never be 0. It will block for at least one byte to be read (in which case the return value will be 1 or more), or for the end of the stream to be reached (in which case the return value will be -1).

people

See more on this question at Stackoverflow