2014-09-12 32 views
0

我有一個壓縮的文件。Inflater獲取壓縮方法

使用Inflater類,我可以解壓縮它,但是當我使用Deflater再次壓縮它時,兩個文件都不相同。

我已經試圖改變壓縮級別最好...

public static String compress(byte[] rawData) 
{ 
    Deflater compressor = new Deflater(); 

    byte[] byteBuffer = new byte[1024]; 
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
      rawData.length); 

    compressor.setInput(rawData); 
    compressor.setLevel(Deflater.BEST_COMPRESSION); 
    compressor.finish(); 

    while (!compressor.finished()) 
    { 
     outputStream.write(byteBuffer, 0, 
       new Integer(compressor.deflate(byteBuffer))); 
    } 

    return new String(outputStream.toByteArray()); 
} 

...,結果是更接近原始。

這裏是我的吹氣代碼:

public static String decompress(byte[] compressed) 
     throws DataFormatException 
{ 
    Inflater decompressor = new Inflater(); 

    byte[] byteBuffer = new byte[1024]; 
    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(
      compressed.length); 

    decompressor.setInput(compressed); 

    while (!decompressor.finished()) 
    { 
     outputStream.write(byteBuffer, 0, 
       new Integer(decompressor.inflate((byteBuffer)))); 
    } 

    return new String(outputStream.toByteArray()); 
} 

我如何找出哪些選項已初步被以重建從解壓一個原始文件使用?我新近壓縮的文件不符合規定。

+0

出於好奇,你爲什麼需要這樣做? – Boann 2014-09-12 17:25:38

+0

@Boann:我得到了一個帶有腳本的壓縮文件,我想要修改和重建。沒有關於它的詳細信息 – BullyWiiPlaza 2014-09-12 17:34:02

+0

@ user3764804但是,爲什麼它應該使用什麼精確的壓縮器設置,只要它可以通過任何兼容的解壓縮器進行解壓縮? – Boann 2014-09-12 17:35:42

回答

1

我強烈懷疑你的問題是由這一行造成的:

return new String(outputStream.toByteArray()); 

String(byte[])構造函數使用一個未指定的依賴於平臺的字符集,其可以任意破壞了二進制數據轉換字節字符,因爲不是所有可能的字節相當於以有效的字符。不保證new String(someBytes).getBytes()等於someBytes。您應該返回字節數組。

+0

是的! :) 轉換爲字符串搞砸了,謝謝很多人! 文件現在完全相同。 – BullyWiiPlaza 2014-09-12 18:24:49

+0

+1好答案! – EvenPrime 2014-09-12 18:25:04