2014-05-12 79 views
3

我有一個壓縮和解壓縮字節數組的類;使用GzipInputStream解壓縮到一個字節[]

public class Compressor 
{ 
    public static byte[] compress(final byte[] input) throws IOException 
    { 
     try (ByteArrayOutputStream bout = new ByteArrayOutputStream(); 
       GZIPOutputStream gzipper = new GZIPOutputStream(bout)) 
     { 
      gzipper.write(input, 0, input.length); 
      gzipper.close(); 

      return bout.toByteArray(); 
     } 
    } 

    public static byte[] decompress(final byte[] input) throws IOException 
    { 
     try (ByteArrayInputStream bin = new ByteArrayInputStream(input); 
       GZIPInputStream gzipper = new GZIPInputStream(bin)) 
     { 
      // Not sure where to go here 
     } 
    } 
} 

如何解壓輸入並返回一個字節數組?

注意:由於字符編碼問題,我不想對字符串進行任何轉換。

回答

7

丟失的代碼將會像

byte[] buffer = new byte[1024]; 
ByteArrayOutputStream out = new ByteArrayOutputStream(); 

int len; 
while ((len = gzipper.read(buffer)) > 0) { 
    out.write(buffer, 0, len); 
} 

gzipper.close(); 
out.close(); 
return out.toByteArray(); 
+0

會讀取方法填充數據,如果它沒有字節填充了1024?還是隻能得到相同大小的確切數據? –

+1

它只是一個緩衝區。如果讀取的字節數量(len) Leo

+1

這裏的重要事情是,使用緩衝區時,在將數據從一個流複製到另一個流時,不會有任何內存不足的風險。 – Leo

相關問題