How does the InputStream.read(byte[]) method know if the "End of Stream" has been reached and return "-1" ?
What are all the conditions for returning "-1" ?
How to detect an "End of Stream" (without sending an integer which contains the total number of bytes to read before) ?
Example of use:
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);
}
InputStream
is an abstract type with many implementations. AFileInputStream
, for example, will return-1
if you have reached the end of the file. If it's a TCP socket, it will return -1 if the connection has been closed. It is implementation-dependent how end-of-stream is determined.