Video in progress
When does InputStream.read() return -1, and what does it mean?
-1 means the end of the stream was reached (EOF) and there is no more data. When reading a single byte, read() returns a value from 0 to 255 as an int, so -1 is never confused with a real byte.
📖 Answer
Why does it return an int and not a byte? Because the byte range is -128..127 and leaves no room for an "end" marker. With an int you can fit 256 byte values plus a separate -1.
The classic read loop:
try (InputStream in = Files.newInputStream(path)) {
byte[] buf = new byte[8192];
int n;
while ((n = in.read(buf)) != -1) {
process(buf, 0, n); // use only n bytes!
}
}
A common mistake is ignoring n and using the whole buf. In the last chunk the buffer is half full, and the rest holds "garbage" left from the previous iteration.
When reading from a socket, -1 means the other side closed the connection. If the data hasn't arrived yet, read() simply blocks and waits.
Sign up to mark studied questions and save your progress.