javainputstreambytearrayoutputstreamgzipoutputstreamioutils

Compress InputStream with GZIPOutputStream into ByteArray


I have a method that takes an InputStream as a parameter and I'm trying to compress the input stream using GZIPOutputStream and then return a compressed byte array. My code looks like this:

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

But somehow it doesn't seem to be working. I'm trying to perform unit testing on this with the following code:

    @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();
    }
}

But I'm getting this exception

java.io.EOFException: Unexpected end of ZLIB input stream

What I'm i doing wrong?


Solution

  • Flushing and closing the output stream after copying the input stream into the output stream fixed the issue:

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