Input stream.read return 0 or -1?

The Javadocs for InputStream.read() say:

If the length of b is zero, then no bytes are read and 0 is returned

In normal use, this should never happen, so there's not much point to testing for this condition explicitly. (If you want to avoid looping forever because the buffer is zero-length and fail-fast in this situation, just test the length of the buffer.)

Further on, there's:

Returns: the total number of bytes read into the buffer, or -1 if there is no more data because the end of the stream has been reached.

If you want to test for end-of-file (or network stream, or whatever), use the test:

if ( inputStream.read(buffer) != -1 ) ...

A non-buggy Java implementation will never return anything else to indicate there's no more data available.


If you already know that the buffer length is not zero, there is no effective difference between these two expressions. Given this basic stipulation about a valid buffer, it can be inferred from the docs that read will never return 0.

This method blocks until input data is available, end of file is detected, or an exception is thrown.

Tags:

Java