用Java解压缩GZIP字符串

veg*_*dio 6 java

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

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

byte[] gzip = getGZIPByteArray();

/* Code do uncompress the GZIP */

System.out.print(uncompressedGZIP);
Run Code Online (Sandbox Code Playgroud)

任何人都可以帮我处理中间的代码吗?

Nov*_*zen 12

// 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();
Run Code Online (Sandbox Code Playgroud)


ver*_*ude 7

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

    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();
    }
Run Code Online (Sandbox Code Playgroud)

确保在类路径中包含以下内容,并import在代码中使用它们.

import java.util.zip.*;
import org.apache.commons.io.IOUtils;
Run Code Online (Sandbox Code Playgroud)