liveBook · Manning

readNBytes method

As explained in 100 Java Mistakes and How to Avoid Them

The readNBytes method reads up to or the requested number of bytes from an input stream, with an overload that returns a new byte array.

Use InputStream.readNBytes() instead of the older read(byte[]) pattern when a read operation should have a clearer result interface. Available since Java 11, it may block repeatedly until the requested number of bytes is read; use its returned result rather than assuming a supplied buffer was fully populated. section 2.11

void readPrefix(InputStream is) throws IOException { 
  byte[] arr = new byte[100]; 
  is.read(arr); 
  process(arr); 
}

This older pattern processes the whole 100-byte array without checking how many bytes read() actually returned. Prefer an API whose returned result is part of the operation’s normal use. section 2.11

Avoid partial-read mistakes:

  • Read the Javadoc before adopting an unfamiliar I/O method, including its blocking behavior and result handling. section 2.11
  • Do not ignore a method result merely because it also receives a mutable argument. section 2.11

How 100 Java Mistakes and How to Avoid Them covers it

How deep it goes
Explains its Java 11 availability and repeated blocking behavior, while deferring detailed overload semantics to Javadoc.
Examples
Contrasts read(byte[]) followed by processing an entire fixed-size buffer.
What it assumes
Assumes familiarity with Java InputStream operations and byte arrays.
What you can do after
Apply readNBytes() as a modern InputStream alternative while accounting for its returned result and possible repeated blocking.
How it connects
Connects InputStream reading with ignored return values, mutable arguments, and Javadoc consultation.

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.