【问题标题】:ObjectInputStream over DeflaterInputStream throws StreamCorruptedException [duplicate]DeflaterInputStream 上的 ObjectInputStream 抛出 StreamCorruptedException [重复]
【发布时间】:2017-05-02 16:32:29
【问题描述】:

我正在尝试使用 ObjectOutputStream 而不是 DeflaterOutputStream 将压缩数据写入底层流。但是,当我尝试使用他们的 InputStream 同行读取数据时,会引发异常。值得注意的是,将Deflate{Output,Input}Stream 替换为GZip{Output,Input}Stream,它按预期工作。显示此行为的示例代码如下所示:

ByteArrayOutputStream baos = new ByteArrayOutputStream();
try(ObjectOutputStream oos = new ObjectOutputStream(new DeflaterOutputStream(baos))) {
    oos.writeObject("test");
}

ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
try(ObjectInputStream oos = new ObjectInputStream(new DeflaterInputStream(bais))) {
    System.out.println(oos.readObject());
}

它会抛出以下异常:

Exception in thread "main" java.io.StreamCorruptedException: invalid stream header: 789CAB98
    at java.io.ObjectInputStream.readStreamHeader(ObjectInputStream.java:857)
    at java.io.ObjectInputStream.<init>(ObjectInputStream.java:349)
    at Main.main(Main.java:23)

有谁知道为什么会发生这种情况?

【问题讨论】:

    标签: java serialization gzip deflate


    【解决方案1】:

    我已经弄清楚了,这是一个愚蠢的错误。但是回答我自己的问题,这样未来的人就不会再上当了:

    DeflaterOutputStream 的逆类是InflaterInputStream,而不是DeflaterInputStream。所以代码应该如下所示:

    ByteArrayOutputStream baos = new ByteArrayOutputStream();
    try(ObjectOutputStream oos = new ObjectOutputStream(new DeflaterOutputStream(baos))) {
        oos.writeObject("test");
    }
    
    ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
    try(ObjectInputStream oos = new ObjectInputStream(new InflaterInputStream(bais))) {
        System.out.println(oos.readObject());
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2020-05-13
      • 2021-07-03
      • 1970-01-01
      • 2013-01-09
      • 1970-01-01
      • 2020-05-03
      • 2013-02-16
      相关资源
      最近更新 更多