It seems dirty to use an exception to indicate the end of a file has been reached. Every file we read has an end, so it doesn't seem exceptional or unexpected. Furthermore, I don't like using an exception for the non-exceptional flow of my program.
I'm talking about using java.io.EOFException to signal the end of a data input stream:
Imagine a file consisting of the following messages...
----------------- ------------------
- 2-byte LENGTH - - N-byte PAYLOAD - , where N = LENGTH;
----------------- ------------------
...and reading this file with DataInputStream:
DataInputStream in = new DataInputStream(...);
...
try {
while (true) {
short length = in.readShort();
byte[] b = new byte[length];
in.readFully(b);
}
} catch (EOFException e) { }
...
In this example, an EOFException is thrown by the call to in.readShort()
. Should I figure out the number of bytes in the file, and read exactly that number of bytes (determined by total -= length
going to zero), and exit the while-loop without an exception? I'm kind of looking for best practice.
Should I do something like this?
long total = file.length();
while (total > 0) {
short length = in.readShort();
total -= length;
byte[] b = new byte[length];
in.readFully(b);
}
The API Specification specifies that EOFException signals an end of file or end of stream has been reached unexpectedly during input. But it's also used by data input streams to signal end of stream.
What do I do when the excepted is expected?