Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Input stream.read return 0 or -1?

Tags:

java

What the difference between

byte[] buffer = new byte[1024];
// this:
if (inputStream.read(buffer) > 0) { /*...*/ }
// and:
if (inputStream.read(buffer) != -1) { /*...*/ }

Can both determine the network stream terminate?

like image 329
Adam Lee Avatar asked Sep 17 '12 13:09

Adam Lee


1 Answers

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.

like image 186
millimoose Avatar answered Oct 01 '22 09:10

millimoose