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?
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 love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With