0

我有一个将 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 输入流的意外结束

我在做什么错?

4

1 回答 1

0

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

         IOUtils.copy(inputStream, gzipOutputStream);
         gzipOutputStream.flush();
         gzipOutputStream.close();
于 2018-02-26T14:55:51.217 回答