【问题标题】:Decompressing a byte[] using GzipInputStream使用 GzipInputStream 解压缩 byte[]
【发布时间】:2014-05-12 09:58:51
【问题描述】:

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

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

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

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

【问题讨论】:

    标签: java compression gzip


    【解决方案1】:

    您丢失的代码将类似于

    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,read 方法是否会填充数据?还是我只会得到相同大小的确切数据?
    • 它只是一个缓冲区。如果读取的字节数(len)
    • 这里重要的是,使用缓冲区,在将数据从一个流复制到另一个流时,您不会有任何内存不足的风险。
    • 当缓冲区填充超过 1024 字节时会发生什么?
    • @Snap gzipper.read(buffer) 保证不会。缓冲区数组被填满,然后循环继续,并覆盖之前的内容,从数组的开头开始
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-15
    • 2011-09-01
    • 2019-09-30
    • 2019-08-06
    • 2012-05-22
    • 1970-01-01
    相关资源
    最近更新 更多