使用GzipInputStream解压缩为byte [] [英] Decompressing to a byte[] using GzipInputStream

查看:93
本文介绍了使用GzipInputStream解压缩为byte []的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a class that compresses and decompresses a byte array;

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

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

How do I decompress the input and return a byte array?

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

Note: I don't want to do any conversion to strings because of character encoding issues.

推荐答案

丢失的代码类似于

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

这篇关于使用GzipInputStream解压缩为byte []的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆