Question

I'm trying to compress and decompress some bytes of data with the Deflater and InflaterOutputStream.

The problem is that compression seems to work (I'm not sure since the compressed data is always the same even if I have random test data). But the decompression return nothing at all.

What am I doing wrong?

My console output:

Test data: D8A8E00821608F227AE473774E177216

Compressed data: 789C

Decompressed data:

My program:

SecureRandom random = new SecureRandom();
byte[] testdata = new byte[16];
random.nextBytes(testdata);
System.out.println("Test data: " + DatatypeConverter.printHexBinary(testdata));

byte[] compressed = null;
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream())
{
   try (DeflaterOutputStream stream = new DeflaterOutputStream(buffer))
   {
      stream.write(testdata);
      stream.flush();
      compressed = buffer.toByteArray();
      System.out.println("Compressed data: " + DatatypeConverter.printHexBinary(compressed));
   }
}
catch (IOException e)
{
   System.out.println("IOException during compression.");
}

byte[] decompressed = null;
try (ByteArrayOutputStream buffer = new ByteArrayOutputStream())
{
   try (InflaterOutputStream stream = new InflaterOutputStream(buffer))
   {
      stream.write(compressed);
      stream.flush();
      decompressed = buffer.toByteArray();
      System.out.println("Decompressed data: " + DatatypeConverter.printHexBinary(decompressed));
   }
}
catch (IOException e)
{
   System.out.println("IOException during decompression.");
}
Was it helpful?

Solution

The problem is that you're only flushing the stream - which doesn't necessarily mean there's no more data to come, which can affect the decompression.

If you change both of your flush() calls to close(), you'll see you get the appropriate data back... or as you're using a try-with-resources statement, just let that close the inner stream, and wait until after that to call toByteArray:

try (ByteArrayOutputStream buffer = new ByteArrayOutputStream())
{
   try (DeflaterOutputStream stream = new DeflaterOutputStream(buffer))
   {
      stream.write(testdata);
   }
   compressed = buffer.toByteArray();
   System.out.println("Compressed data: " + Arrays.toString(compressed));
}
catch (IOException e)
{
   System.out.println("IOException during compression.");
}

(Ditto when decompressing.)

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top