使用GZIPOutputStream将InputStream压缩到ByteArray中

时间:2018-02-26 02:02:03

标签: java inputstream bytearrayoutputstream gzipoutputstream ioutils

我有一个方法,它将InputStream作为参数,我正在尝试使用GZIPOutputStream压缩输入流,然后返回一个压缩的字节数组。我的代码如下所示:

    public static byte[] compress(final InputStream inputStream) throws IOException {
    final int byteArrayOutputStreamSize = Math.max(32, inputStream.available());
    try(final ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream(byteArrayOutputStreamSize);
    final GZIPOutputStream gzipOutputStream = new GZIPOutputStream(byteArrayOutputStream)) {
        IOUtils.copy(inputStream, gzipOutputStream);
        return byteArrayOutputStream.toByteArray();
    }
}

但不知怎的,它似乎没有起作用。我正在尝试使用以下代码对此进行单元测试:

    @Test
public void testCompress() throws Exception {
    final String uncompressedBytes = "some text here".getBytes();
    final InputStream inputStream = ByteSource.wrap(uncompressedBytes).openStream();
    final byte[] compressedBytes = CompressionHelper.compress(inputStream);
    Assert.assertNotNull(compressedBytes);
    final byte[] decompressedBytes = decompress(compressedBytes);
    Assert.assertEquals(uncompressedBytes, decompressedBytes);
}

public static byte[] decompress(byte[] contentBytes) throws Exception {
    try (ByteArrayOutputStream out = new ByteArrayOutputStream();
         ByteArrayInputStream byteArrayInputStream = new ByteArrayInputStream(contentBytes);
         InputStream inputStream = new GZIPInputStream(byteArrayInputStream)) {
        IOUtils.copy(inputStream, out);
        return out.toByteArray();
    }
}

但我得到了这个例外

  

java.io.EOFException:ZLIB输入流的意外结束

我做错了什么?

1 个答案:

答案 0 :(得分:0)

将输入流复制到输出流后刷新和关闭输出流解决了问题:

         IOUtils.copy(inputStream, gzipOutputStream);
         gzipOutputStream.flush();
         gzipOutputStream.close();