Video in progress
Why is it a mistake to assume that in.read(buffer) fills the buffer completely?
read(byte[]) reads "at least one and at most the buffer length" bytes, whatever is ready right now. On network and pipes especially, data arrives in pieces. If you need exactly N bytes, use readNBytes or DataInputStream.readFully.
📖 Answer
This bug almost never shows up when testing with a local file, which is what makes it dangerous:
byte[] header = new byte[16];
in.read(header); // 7 bytes may have arrived, not 16
int version = header[12]; // garbage
On a socket, depending on how the TCP packets arrive, the first read can give 7 bytes and the second the remaining 9.
The correct options:
byte[] header = in.readNBytes(16); // Java 11+
if (header.length < 16) throw new EOFException("Header to'liq emas");
// or
new DataInputStream(in).readFully(header); // EOFException if not enough
readNBytes(byte[], off, len) returns how many bytes it read, and readNBytes(int) returns a new array. Both keep reading until they get the required amount or the stream ends.
The same rule applies to skip(n): it can also skip fewer bytes than you asked for. Java 12+ has skipNBytes.
Sign up to mark studied questions and save your progress.