Reading Single Bytes with read()
You'll learn why InputStream.read() returns an int instead of a byte, and how to detect when you've reached the end of a stream.
The Signature and Return Value
When you call read() on an InputStream, it returns an int value between 0 and 255 to represent the next byte, or -1 when the stream ends (EOF - End of File). This might seem strange at first—why not just return a byte?
Why int Instead of byte?
The answer lies in Java's type system. A byte in Java is signed, ranging from -128 to 127. If read() returned a byte, there would be no way to distinguish between the actual byte value and the end-of-stream signal. Every possible byte value (-128 through 127) represents valid data.
By using int, Java can return the unsigned byte value (0-255) plus reserve -1 as a special "no more data" flag. Think of it like a vending machine: slots 0-255 dispense items, but slot -1 means "out of stock."
Reading and Detecting EOF
FileInputStream fis = new FileInputStream("data.txt");
int byteValue = fis.read();
if (byteValue == -1) {
// End of stream reached
} else {
// byteValue is 0-255, representing the byte that was read
byte actualByte = (byte) byteValue; // cast to byte if needed
}
Always check for -1 before processing the value. A typical reading loop checks this condition to know when to stop.
Key Takeaway: InputStream.read() returns an int (0-255 or -1) rather than a byte to provide a distinct end-of-stream signal without conflicting with valid byte values.