2014-03-04 82 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