在this thread的帮助下我能够编写一个 decompress()
和一个 compress()
函数。我的程序接收压缩形式的数据,对其进行扩充,有时修改它,然后再次重新压缩并发送它。经过几个小时的头痛和 bug 跟踪,我发现有时(!),我使用的 GZIPOutputStream
无法正确关闭。我可以冲洗它,但之后什么也没有发生。然而,在其他时候,它只是有效>.>
这是我的 compress()
方法的代码。
public static byte[] compress(String data) throws IOException {
try (PipedInputStream pipedIn = new PipedInputStream();
GZIPOutputStream compressor= new GZIPOutputStream(new PipedOutputStream(pipedIn))) {
compressor.write(data.getBytes("UTF-8"));
compressor.flush();
compressor.close();
// Sometimes does not reach this point.
return IOUtils.toByteArray(pipedIn);
}
}
出于调试目的,我添加了一些 System.Outs。控制台输出如下:
------------------------------------
Decompressing ...
compressed byte count: 628
uncompressed byte count: 1072
------------------------------------
Compressing ...
uncompressed byte count: 1072
compressed byte count: 628
------------------------------------
>>> That worked!
------------------------------------
Decompressing ...
compressed byte count: 526
uncompressed byte count: 2629
------------------------------------
uncompressed byte count: 2629
compressed byte count: 526
------------------------------------
>>> That worked!
------------------------------------
Decompressing ...
compressed byte count: 1888
uncompressed byte count: 6254
------------------------------------
此后,什么也没有发生。任何有关此问题的帮助将不胜感激!
最佳答案
您对 GZIP 流的使用可能没有任何问题;相反,这是您使用管道流的方式。它们用于线程间通信,并且当您按自己的方式使用它们时会阻塞。
而是使用ByteArrayOutptuStream
来捕获输出。
关于Java gzip - GZIPOutputStream 不任意关闭/压缩,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33369459/