Is Java an EOFException?

It seems messy to use an exception to indicate that the end of the file has been reached. Each file you read has an end, so it does not seem exceptional or unexpected. Also, I don't like to use an exception for the non-exclusive flow of my program.

I am 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 using a DataInputStream:

DataInputStream in = new DataInputStream(...);

...

try {
    while (true) {
        short length = in.readShort();
        byte[] b = new byte[length];
        in.readFully(b);
    }
} catch (EOFException e) { }

...

EOFException in.readShort(). ( total -= length, ), while ? .

- ?

long total = file.length();
while (total > 0) {
    short length = in.readShort();
    total -= length;
    byte[] b = new byte[length];
    in.readFully(b);
}

API , EOFException , . .

, ?

+5
3

DataInput.readFully:

 This method blocks until one of the following conditions occurs:

    * b.length bytes of input data are available, in which case a normal return is made.
    * End of file is detected, in which case an EOFException is thrown.
    * An I/O error occurs, in which case an IOException other than EOFException is thrown.

, , b.length, , , - -, , b.length bytes .

, , DataInput.readFully. , , , , , .

+2

, . , ( " " ) ( " " ).

, , - .

- , . , , EOF. - . , ( IOException). , EOF.

, . , API C (POSIX). , . , , . , . , , , .

+1

, readFully , . EOF , , . read, read.

0

All Articles