0
votes

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?

1
Define 'somehow when I compress it'. - user207421
I updated the description to be more clear - Jesus
Sigh. You need to post your decompresson code, by which I do not mean posting the code that calls your decompression code. - user207421
Sorry I forgot, I updated again. - Jesus
Evidently IOUtils.copy() doesn't close the output stream, so you have do that yourself. NB Your use of available() is both invalid and unnecessary. - user207421

1 Answers

0
votes

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