'Input stream.read return 0 or -1?
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?
Solution 1:[1]
The Javadocs for InputStream.read() say:
If the length of
bis 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
-1if 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.
Solution 2:[2]
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.
Solution 3:[3]
There is indeed a difference between inputstream.read(buffer) !=-1 and inputstream.read(buffer) > 0. I recently experienced this while using jSerialComm library. When reading from an RS-232 serial port and a BREAK signal is received the InputStream (which I retrieved using the SerialPort.getInputStream() method) actually returns 0. This is quite useful when doing blocking I/O operations on an RS-232 serial port, for example using the BREAK signal (a 0-length read from the input stream) one can determine the end of a request/response message.
Solution 4:[4]
According to the doc, inputstream.read(buffer) !=-1 will tell you that the stream is ended. inputstream.read(buffer) == 0 just says that there are no bytes available to read but the stream is still active (i.e. the peer just hasn't sent anything since you last read everything you could).
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | |
| Solution 2 | Brent Bradburn |
| Solution 3 | |
| Solution 4 | mprivat |
