在 Java 中解压缩 GZIP 字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/12531579/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-31 09:16:10  来源:igfitidea点击:

Uncompress a GZIP string in Java

java

提问by vegidio

Possible Duplicate:
How to decompress a gzipped data in a byte array?

可能的重复:
如何解压缩字节数组中的 gzip 数据?

I have a Gzip'd byte array and I simply want to uncompress it and print the output. It's something like this:

我有一个 Gzip'd 字节数组,我只想解压缩它并打印输出。它是这样的:

byte[] gzip = getGZIPByteArray();

/* Code do uncompress the GZIP */

System.out.print(uncompressedGZIP);

Can anybody help me with the code in the middle?

有人可以帮我处理中间的代码吗?

回答by NovaDenizen

// With 'gzip' being the compressed buffer
java.io.ByteArrayInputStream bytein = new java.io.ByteArrayInputStream(gzip);
java.util.zip.GZIPInputStream gzin = new java.util.zip.GZIPInputStream(bytein);
java.io.ByteArrayOutputStream byteout = new java.io.ByteArrayOutputStream();

int res = 0;
byte buf[] = new byte[1024];
while (res >= 0) {
    res = gzin.read(buf, 0, buf.length);
    if (res > 0) {
        byteout.write(buf, 0, res);
    }
}
byte uncompressed[] = byteout.toByteArray();

回答by verisimilitude

The below method may give you a start :-

下面的方法可能会给你一个开始:-

    public static byte[] decompress(byte[] contentBytes){
        ByteArrayOutputStream out = new ByteArrayOutputStream();
        try{
            IOUtils.copy(new GZIPInputStream(new ByteArrayInputStream(contentBytes)), out);
        } catch(IOException e){
            throw new RuntimeException(e);
        }
        return out.toByteArray();
    }

Ensure that you have the below in your classpath and importthem in your code.

确保您的类路径中有以下内容,而import代码中有它们。

import java.util.zip.*;
import org.apache.commons.io.IOUtils;