【问题标题】:How to get the length of the original array according to the compressed byte array of GZIP?如何根据GZIP的压缩字节数组得到原始数组的长度?
【发布时间】:2019-07-30 12:12:01
【问题描述】:

在解压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();
        }

【问题讨论】:

    标签: java io gzip


    【解决方案1】:

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

    这个类实现了一个输出流,其中的数据是 写入字节数组。缓冲区随着数据自动增长 写给它。

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

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

    【讨论】:

      猜你喜欢
      • 2013-01-24
      • 2015-02-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多