使用GzipInputStream解压缩byte[]

7

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

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

我该如何解压输入并返回一个字节数组?
注意:由于字符编码问题,我不想进行任何字符串转换。
1个回答

11

你缺失的代码应该是这样的

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();

读取方法会在数据不足填满1024字节时进行填充吗?还是我只能得到完全相同大小的确切数据? - Joshua Kissoon
1
这只是一个缓冲区。如果读取的字节数(len)< 缓冲区大小,则它将只从0读取到len。 - Leo
2
重要的是,使用缓冲区,在从一个流复制数据到另一个流时,您不会有任何内存耗尽的风险。 - Leo
1
当缓冲区填满超过1024字节时会发生什么? - Snappawapa
@Snap gzipper.read(buffer) 保证不会这样。缓冲区数组被填充,然后循环继续,并覆盖先前的内容,从数组的开头开始。 - OneCricketeer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接