Java Socket - how does the read () method know if the end of the stream has been reached?
-
How does InputStream.read (byte []) know if "end of stream" has been reached and "-1" is returned?
-
What are all the conditions for a "-1" return?
-
How do I detect the "end of stream" (without sending an integer that contains the total number of bytes read previously)?
Usage example:
InputStream input = socket.getInputStream();
ByteArrayOutputStream baos = new ByteArrayOutputStream();
byte[] buffer = new byte[1024];
for(int size = -1; (size = input.read(buffer)) != -1; ) {
baos.write(buffer, 0, size);
}
+3
source to share
1 answer
InputStream
is an abstract type with many implementations. A FileInputStream
, for example, will return -1
if you have reached the end of the file. If it is a TCP socket, it will return -1 if the connection was closed. It is implementation dependent how the final stream is defined.
+3
source to share