Array-taking InputStream.read returns the number of bytes actually read. It may fill only part of the buffer, even when more data exists, because it blocks at most once. At end of stream it returns -1 and writes nothing into the array. section 2.11
void readPrefix(InputStream is) throws IOException {
byte[] arr = new byte[100];
is.read(arr);
process(arr);
}
This code wrongly assumes that read fills all 100 array elements. Processing the whole buffer can include bytes that were not read during this call. section 2.11
Avoid the mistake by handling the result:
- Check for -1 before processing data, since no array bytes are written at end of stream. section 2.11
- Use the returned count to identify exactly which buffer bytes were read; do not assume the array is full. section 2.11
- Treat ignored-read-result warnings as useful guidance, while recognizing that deciding whether every return value matters is not universally mechanical. section 2.11
