使用GzipInputStream解压缩到byte []

Jos*_*oon 4 java compression gzip

我有一个压缩和解压缩字节数组的类;

public class Compressor
{
    public static byte[] compress(final byte[] input) throws IOException
    {
        try (ByteArrayOutputStream bout = new ByteArrayOutputStream();
                GZIPOutputStream gzipper = new GZIPOutputStream(bout))
        {
            gzipper.write(input, 0, input.length);
            gzipper.close();

            return bout.toByteArray();
        }
    }

    public static byte[] decompress(final byte[] input) throws IOException
    {
        try (ByteArrayInputStream bin = new ByteArrayInputStream(input);
                GZIPInputStream gzipper = new GZIPInputStream(bin))
        {
            // Not sure where to go here
        }
    }
}
Run Code Online (Sandbox Code Playgroud)

如何解压缩输入并返回字节数组?

注意:由于字符编码问题,我不想对字符串进行任何转换.

Leo*_*Leo 8

你丢失的代码就像是

byte[] buffer = new byte[1024];
ByteArrayOutputStream out = new ByteArrayOutputStream();

int len;
while ((len = gzipper.read(buffer)) > 0) {
    out.write(buffer, 0, len);
}

gzipper.close();
out.close();
return out.toByteArray();
Run Code Online (Sandbox Code Playgroud)

  • 这里重要的是,使用缓冲区,将数据从一个流复制到另一个流时不会有内存不足的风险。 (2认同)