1

我正在尝试使用 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.");
}
4

1 回答 1

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

(解压时同上。)

于 2013-08-31T10:00:00.513 回答