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
