gpt4 book ai didi

java - Android Deflator 内存不足错误

转载 作者:行者123 更新时间:2023-12-01 13:48:02 26 4
gpt4 key购买 nike

我想在保存到文件之前压缩字节数组。当我使用 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);

最佳答案

我认为有一个更简单的解决方案:

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

关于java - Android Deflator 内存不足错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20197859/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com