java - 如何根据GZIP的压缩字节数组得到原数组的长度?

标签 java io gzip

在解压GZIP压缩的数组之前,我想知道原始数组的长度,以便申请合适的缓冲区数组。例如下面代码中的“1024”。谢谢!

        byte[] buffer = new byte[1024];
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        try (ByteArrayInputStream bin = new ByteArrayInputStream(localByteBuf);
             GZIPInputStream gis = new GZIPInputStream(bin)) {
            int len;
            while ((len = gis.read(buffer)) > 0) {
                out.write(buffer, 0, len);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }

最佳答案

ByteArrayOutputStream 将负责内部 byte[] 数组的增长。根据类 javadoc:

This class implements an output stream in which the data is written into a byte array. The buffer automatically grows as data is written to it.

您很可能希望使用 InputStream.transferTo() 复制流使代码更具可读性:

ByteArrayOutputStream out = new ByteArrayOutputStream(); // default 32 size
GZIPInputStream in = new GZIPInputStream(
        new ByteArrayInputStream(localByteBuf)));
in.transferTo(out);

关于java - 如何根据GZIP的压缩字节数组得到原数组的长度?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57271389/

相关文章:

c++ - 初始化标准流对象

iphone - 在 PHP 中使用 gzcompress;需要能够在 iPhone 上解压缩

android - 如何在 Android 2.2 或更高版本中展开压缩的 tar 文件

java - 在 Java 中生成 VAPID key 并将其传递给 JavaScript PushManager

java - Spring从applicationContext获取bean的正确方法

java - IndexOutOfBounds 异常处理

Java = 下载缓冲区未填满?冲洗/缓冲如何工作?

java - JFreeChart PeriodAxis :29 minutes fractions

Java - 读取 BZ2 文件并即时解压缩/解析

Heroku Cedar和Nginx(gzip)