Android Deflator内存不足错误

时间:2013-11-25 16:18:03

标签: java android zlib

我想在保存到文件之前压缩字节数组。 当我使用Deflator压缩字节数组时,我得到OutOfMemoryError

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);

1 个答案:

答案 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();
}