2013-11-25 61 views
0

我想在保存到文件之前先壓縮字節數組。 當我用平減指數來壓縮字節數組,我得到OutOfMemoryErrorAndroid Deflator內存不足錯誤

ERROR/dalvikvm-heap(16065): Out of memory on a 921616-byte allocation. 

I check the code and it is the same as android developer。但我添加了DeflatorOutputStream以減少內存使用量。

我的代碼:

public static byte[] compress(byte[] data) throws IOException { 

    Deflater deflater = new Deflater(); 
    deflater.setInput(data); 
    deflater.finish(); 

    ByteArrayOutputStream outputStream = new ByteArrayOutputStream(data.length); 
    DeflaterOutputStream dos=new DeflaterOutputStream(outputStream); 

    byte[] buffer = new byte[1024]; 
    while (!deflater.finished()) { 
     int count=deflater.deflate(buffer); 
     // returns the generated code... index 
     dos.write(buffer, 0, count); 
    } 

    deflater.end(); 
    byte[] output = outputStream.toByteArray(); 

    dos.finish(); 
    dos.close(); 
    outputStream.close(); 

    return output; 
} 

我檢查這個錯誤發生在這條線:int count=deflater.deflate(buffer);

+0

的DeflaterOutputStream將再次做通縮!所以你要壓縮兩次。 – isnot2bad

+0

好的,但這並不能解決內存不足錯誤 –

回答

1

,我認爲有一個更簡單的解決方案:

public static byte[] compress(byte[] data) throws IOException { 
    ByteArrayOutputStream bout = new ByteArrayOutputStream(data.length); 
    try (DeflaterOutputStream out = new DeflaterOutputStream(bout)) { 
     out.write(data); 
    } 

    return bout.toByteArray(); 
} 
+0

謝謝你的回答,但我得到了同樣的錯誤 –

+0

然後,我假設你的數據陣列太大或太多的內存消耗在某處之前。你的數據數組有多大? – isnot2bad

+0

壓縮前1500kb和壓縮後400kb。我每100ms調用一次壓縮函數。可能是內存沒有時間釋放? –