2014-03-04 36 views
1

下面提到的是我制作的一个演示程序,用于验证Deflator和Inflator类的功能。我的主要方法内部第一次压缩和解压缩相同的压缩数据给出了不同的结果

的源代码: -

byte[] decom = {49, 52, 49, 53, 56, 52, 56, 50, 53, 54, 55, 54, 53, 0, 50, 0, 
    52, 0, 79, 98, 106, 101, 99, 116, 78, 97, 109, 101, 50, 0, 85, 115, 101, 114, 
    50, 0, 86, 97, 108, 117, 101, 52, 0}; 

byte[] compressedData = new byte[decom.length]; 
Deflater compressor = new Deflater(); 
compressor.setInput(decom); 
System.out.println("Decompressed data : " + Arrays.toString(decom));  
compressor.finish(); 

int sizeofCompressedData = compressor.deflate(compressedData);  
System.out.println("Compressed data : " + Arrays.toString(compressedData)); 

Inflater inflater = new Inflater(); 
byte[] decompressed = new byte[decom.length]; 
inflater.setInput(compressedData, 0, sizeofCompressedData); 

try 
{ 
    inflater.inflate(decompressed); // resultLength 
} 
catch (DataFormatException e) 
{ 
    decompressed = null; 
} 

System.out.println("Compressed data decompressed again: " 
    + Arrays.toString(decompressed)); 

编译并运行它后,我得到以下的输出: -

解压的数据:49,52,49,53,56,52 ,56,50,53,54,55,54,53,0,50,0,52,0,79,98,106,101,99,116,78,97,109,101,50,08,85,90,95,90,95,90,95,90,90,95,90,90,95,90,95,90,95,90,95,90,95,90,95,90,95,90,95,90,95,90,95,90,95,90,95,95,90,95, ,115,101,114,50,0,86,97,108,117,101,52,0]

压缩数据:[120,-100,51,52,49,52,-75,48 ,-79,48,50,53,51,55,51,101,48,98,48,97,-16,79,-54, 74,77,46,-15,75,-52,77,53,98,8,45,78,45,50,98,8,75,-52,41,77]

压缩数据解压缩[49,52,49,53,56,52,56,50,53,54,55,54,53,0,50,0,52,0,79,98,106,101,99,116 ,78,97,109,101,50,0,85,105,101,114,50,0,86,97,108,117,0,0,0]

正如你在上面看到的那样,压缩数据和膨胀压缩数据后生成的数据不一样。请帮助。

+0

好吧,没有没有使用哪个编解码器。我删除了我的评论。 –

回答

1

如果你有尝试:

byte[] compressedData = new byte[ decom.length + 2 ]; 

...它的工作原理。看起来您的压缩数据比解压缩的数据占用的空间更多。

+1

打败我吧。另外,如果你在'deflate()'后面打印'compressor.finished()',你会得到'false',表示它想要写更多的数据。同样,在解压后'inflator.finished()'是错误的。为了健壮,它需要一个循环。或者使用流媒体版本。 – slim