我有一个返回字节数组的API调用 . 我当前将结果流式传输到字节数组,然后确保校验和匹配,然后将ByteArrayOutputStream写入File . 代码是这样的,它运行得很好 .
String path = "file.txt";
ByteArrayOutputStream byteBuffer = new ByteArrayOutputStream();
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
byteBuffer.write(buffer, 0, len);
}
FileOutputStream stream = new FileOutputStream(path);
stream.write(byteBuffer.toByteArray());
我担心输入流的结果可能大于android中的堆大小,如果整个字节数组在内存中,我可能会得到OutOfMemory异常 . 将inputStream写入文件块的最优雅方法是什么,这样字节数组永远不会大于堆大小?
2 回答
不要写入
ByteArrayOutputStream
. 直接写入FileOutputStream
.我接受了建议跳过ByteArrayOutputStream并写入FileOutputStream,这似乎解决了我的顾虑 . 通过一个快速调整,FileOutputStream由BufferedOutputStream修饰