简体   繁体   English

使用GzipInputStream解压缩到byte []

[英]Decompressing to a byte[] using GzipInputStream

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. 注意:由于字符编码问题,我不想对字符串进行任何转换。

your missing code will be something like 你丢失的代码就像是

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM