[英]Compress InputStream with GZIPOutputStream into ByteArray
我有一个将 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 输入流意外结束
我做错了什么?
将输入流复制到输出流后刷新和关闭输出流修复了该问题:
IOUtils.copy(inputStream, gzipOutputStream);
gzipOutputStream.flush();
gzipOutputStream.close();
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.