如何读取DataInputStream到最后而无需捕获EOFException? [英] How to read DataInputStream until the end without needing to catch an EOFException?

查看:476
本文介绍了如何读取DataInputStream到最后而无需捕获EOFException?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我们有一些二进制数据 byte []数据,其中仅包含整数。如果我想使用 DataInputStream 读取此数据,则只能想到以下方法:

Suppose we have some binary data byte[] data that only contains Integers. If I wanted to read this data utilizing a DataInputStream, the only approach I can come up with is the following:

DataInputStream in = new DataInputStream(new ByteArrayInputStream(data));
try {
    while (true){
        int i = in.readInt();
    }
} catch (EOFException e) {
    // we're done!
} catch (IOException e){
    throw new RuntimeException(e);
}

让我感到烦恼的是,期望到达流的结尾并且只有在没有抛出异常的情况下,它才会例外,这是IMO首先击败了异常的目的。

What bugs me about this is that reaching the end of the stream is expected and it would exceptional only if no exception was thrown, what IMO defeats the purpose of exceptions in the first place.

使用Java NIO的 IntBuffer ,没有这种问题。

When using Java NIO's IntBuffer, there's no such problem.

IntBuffer in = ByteBuffer.wrap(data).asIntBuffer();
while (in.hasRemaining()){
    int i = in.get();
}

来自C#并且正在学习Java,我拒绝相信

Coming from C# and being in the process of learning Java I refuse to believe that this is the intended way of doing this.

此外,我 just 碰到了Java NIO,它似乎很新。我在这里使用 IntBuffer 拖延时间。无论如何,我想知道如何在Java中正确完成此操作。

Moreover, I just came across Java NIO which seems to be "quite new". Using IntBuffer here instead would be my way of procrastinating the matter. Regardless, I wanna know how this is properly done in Java.

推荐答案

您不能。 readInt()可以返回任何整数值,因此需要带外机制来指示流的结束,因此引发异常。这就是API的设计方式。您无能为力。

You can't. readInt() can return any integer value, so an out-of-band mechanism is required to signal end of stream, so an exception is thrown. That's how the API was designed. Nothing you can do about it.

这篇关于如何读取DataInputStream到最后而无需捕获EOFException?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆