liveBook · Manning

Read method

As explained in 100 Java Mistakes and How to Avoid Them

The InputStream read method reads bytes into a buffer or returns a byte or end-of-stream indicator depending on its overload.

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

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains partial reads, single blocking behavior, and the -1 result without detailing stream implementations.
Examples
Uses a 100-byte buffer passed to read and then incorrectly processed as wholly populated.
What you can do after
Diagnose/debug with it by distinguishing valid bytes from unused buffer contents after a read call.
How it connects
Connects InputStream.read to Reader.read, end of stream, return values, and static analysis.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of 100 Java Mistakes and How to Avoid Them. The section links point to the parts of the book it draws on.