Java通缩/通胀流如何运作?

时间:2013-08-31 09:51:53

标签: java inflate deflate

我正在尝试使用Deflater和InflaterOutputStream压缩和解压缩一些字节数据。

问题在于压缩似乎有效(我不是 确保即使我有随机测试数据,压缩数据总是相同的)。 但减压根本没有回报。

我做错了什么?

我的控制台输出:

测试数据:D8A8E00821608F227AE473774E177216

压缩数据:789C

解压缩数据:

我的节目:

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.");
}

1 个答案:

答案 0 :(得分:2)

问题是你只是刷新流 - 这并不一定意味着没有更多数据可以来,这会影响解压缩。

如果您将flush()两次调用都更改为close(),则会看到您收到相应的数据......或者当您使用try-with-resources语句时,让它关闭内部流,并等到那之后调用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.");
}

(解压缩时也一样。)