我正在尝试使用ObjectOutputStream超过DeflaterOutputStream将压缩数据写入底层流。但是当我尝试用 InputStream 读取数据时对应,则抛出异常。值得注意的是,替换 Deflate{Output,Input}StreamGZip{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()); 
} 


评论关闭
IT干货网

微信公众号号:IT虾米 (左侧二维码扫一扫)欢迎添加!