Java的EOFException是特殊的吗?

Mr.*_*ite 5 java io exception inputstream eofexception

使用异常来指示已到达文件的末尾似乎很脏.我们阅读的每个文件都有一个结尾,所以它似乎并不特殊或意外.此外,我不喜欢对我的程序的非异常流程使用异常.

我正在谈论使用java.io.EOFException来表示数据输入流的结束:

想象一个包含以下消息的文件......

----------------- ------------------
- 2-byte LENGTH - - N-byte PAYLOAD - , where N = LENGTH;
----------------- ------------------
Run Code Online (Sandbox Code Playgroud)

...并使用DataInputStream读取此文件:

DataInputStream in = new DataInputStream(...);

...

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

...
Run Code Online (Sandbox Code Playgroud)

在此示例中,调用将抛出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);
}
Run Code Online (Sandbox Code Playgroud)

API规范指定在输入期间EOFException 意外地表示文件的结尾或流的结尾.但它也被数据输入流用于信号流的结束.

预计例外时我该怎么办?

dcp*_*dcp 2

方法参考API规范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.
Run Code Online (Sandbox Code Playgroud)

因此,它的想法是,它要么要读取 b.length 字节的数据,要么如果无法执行此操作,则会出现错误,原因可能是 I/O 错误,或者在读取 b.length 字节之前已到达文件末尾。

因此,您应该在调用之前知道要读取多少字节DataInput.readFully。如果超出文件末尾,则被视为异常行为,因此这就是您收到异常的原因。