简体   繁体   English

Java gzip-GZIPOutputStream无法任意关闭/压缩

[英]Java gzip - GZIPOutputStream not closing / compressing arbitrarily

With the help of this thread I was able to write a decompress() and a compress() function. 借助该线程,我能够编写一个decompress()compress()函数。 My programme receives data in gzipped form, inflates it, sometimes modifies it, then re-compresses it again and sends it along. 我的程序以gzip压缩形式接收数据,对其进行膨胀,有时对其进行修改,然后再次对其进行重新压缩并发送。 After hours of headache and bug tracing, I was able to find out that sometimes(!) , the GZIPOutputStream that I use just won't close properly. 经过数小时的头痛和错误跟踪,我发现有时候(!) ,我使用的GZIPOutputStream无法正确关闭。 I am able to flush it but after that, nothing happens. 我可以冲洗它,但是此后什么也没发生。 However, at other times, it simply works >.> 但是,在其他时候,它只是可以正常工作。

This is the code of my compress() method. 这是我的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);
    }
}

For debugging purposes, I added a few System.Outs. 为了调试,我添加了一些System.Outs。 The console output was as follows: 控制台输出如下:

------------------------------------
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
------------------------------------

After that, nothing happens. 在那之后,什么也没有发生。 Any help with this problem would be greatly appreciated! 任何有关此问题的帮助将不胜感激!

There is probably nothing wrong with your usage of GZIP streams; 您对GZIP流的使用可能没有错; rather it is the way you use the Piped streams. 而是使用管道流的方式。 These are meant for interthread communication and will block when you use them your way. 这些是用于线程间通信的,在您按自己的方式使用它们时会阻塞。

Instead use a ByteArrayOutptuStream to capture the output. 而是使用ByteArrayOutptuStream捕获输出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM