【问题标题】:OutputStream with ByteArrayOutputStream not writingOutputStream 与 ByteArrayOutputStream 不写
【发布时间】:2010-05-28 06:25:53
【问题描述】:

所以我试图将一个对象写出到一个 ByteArray,但由于某种原因它没有写任何东西,我看到返回值为 0,并且读取它会导致例外。

BAoutput = new ByteArrayOutputStream();  
Oout = new ObjectOutputStream(BAoutput);  
Oout.writeObject(receiver);

receiver 是我通过参数获得的对象。 并且例外总是相同的:

java.io.EOFException
  at java.io.ObjectInputStream$BlockDataInputStream.peekByte(Unknown Source)
  at java.io.ObjectInputStream.readObject0(Unknown Source)
  at java.io.ObjectInputStream.readObject(Unknown Source)

有什么想法吗?

大部分代码:(上面有几个定义,没什么意思)

try {
        BAoutput = new ByteArrayOutputStream();
        Oout = new ObjectOutputStream(BAoutput);
        BAinput = new ByteArrayInputStream(BAoutput.toByteArray());
        Oin = new ObjectInputStream(BAinput);

        Oout.writeObject(receiver);
        retval = method.invoke(receiver, args);
        for (Method curr: postMethods){
            curr.setAccessible(true);
            if (curr.invoke(receiver).equals(false)){
                receiver = Oin.readObject();
                throw new PostconditionFailure();
            }
        }           
    } catch (IOException e) {
        e.printStackTrace();
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } finally {
        try {
            Oin.close();
            Oout.close();
            BAinput.close();
            BAoutput.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

【问题讨论】:

  • 你刷新/关闭输出流吗?
  • 实际抛出的异常是什么?
  • 请添加异常的第一行(异常类型和消息)

标签: java serialization bytearray


【解决方案1】:

首先要检查:

  • 刷新/关闭 ObjectOutputStream(正如 Synesso 在他的评论中所述)
  • 确保receiver 是可序列化的(或原始类型)

【讨论】:

  • 我关闭了输出和输入流,但可能不是在正确的时间?另外,我不确定我应该在何时何地冲洗。接收器是可序列化的。此外,添加了例外。当我 ctrl+Ced 时,该行没有被标记。
  • 在打开输入流进行读取之前应关闭输出流,并且可以在最后一次写入后立即刷新输出流。
【解决方案2】:

这对我来说没有多大意义。

所以我试图将一个对象写出一个字节数组,但由于某种原因它没有写任何东西,我从返回值为 0 的事实中看出这一点

什么是返回 0? writeObject 方法根本不返回任何值 - 它是 void 方法!

...而且读取它会导致异常。

这并不一定意味着写入失败。

我认为我们需要查看 >>>所有

编辑

现在我看到了完整的代码,很清楚真正的问题是什么:

    ....
    BAoutput = new ByteArrayOutputStream();
    Oout = new ObjectOutputStream(BAoutput);
    BAinput = new ByteArrayInputStream(BAoutput.toByteArray());
    Oin = new ObjectInputStream(BAinput);
    ...

ByteArrayOutputStream.toByteArray() 方法返回流的当前内容副本。由于尚未向流中写入任何内容,因此字节数组自然为空。

您的问题的解决方案是提取字节数组并构造ByteArrayInputStream 您完成写入Oout 并刷新或关闭它。

【讨论】:

  • 我想我应该更清楚。我的意思是使用 Oin.avaliable() 我知道它没有什么可读的。无论如何,代码在 OP 中。
猜你喜欢
  • 1970-01-01
  • 2015-01-13
  • 2019-09-06
  • 1970-01-01
  • 2011-06-02
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-14
相关资源
最近更新 更多