我正在尝试使用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)
有人知道为什么会发生这种情况吗?
请您参考如下方法:
我已经弄清楚了,这是一个愚蠢的错误。但回答我自己的问题,这样 future 的人就不会再上当了:
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());
}