Handling End-of-File Detection
You'll learn how to reliably detect when you've reached the end of a file using the return values of read() methods.
The Core Idea
When reading from a byte stream, you need to know when there's no more data left. Java uses special return values to signal End-of-File (EOF). Think of it like drinking from a straw—you know you've reached the bottom when you can't pull any more liquid through, not when you've taken a certain number of sips.
Single-Byte Read: Detecting -1
When you call read() to read a single byte, it normally returns a value between 0 and 255. However, when the stream has no more data, read() returns -1:
FileInputStream fis = new FileInputStream("data.txt");
int byteValue;
while ((byteValue = fis.read()) != -1) {
// Process the byte
System.out.print((char) byteValue);
}
fis.close(); // EOF reached, loop exits
Byte Array Read: Watch the Return Value
When you call read(byte[]) or read(byte[], int, int), the method returns how many bytes were actually read. If it returns -1, you've hit EOF:
FileInputStream fis = new FileInputStream("data.txt");
byte[] buffer = new byte[1024];
int bytesRead;
while ((bytesRead = fis.read(buffer)) != -1) {
// Process only bytesRead bytes, not the entire buffer!
System.out.write(buffer, 0, bytesRead);
}
fis.close();
The crucial point: the last read might fill only part of your buffer. If you request 1024 bytes but only 500 remain, read(buffer) returns 500, not -1. The next call returns -1.
Key Takeaway: Always check if read() returns -1 to detect EOF. For array reads, use the return value to know how many bytes are valid—never assume the buffer is full until you see -1.