我有一个返回字节数组的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写入文件块的最优雅方法是什么,这样字节数组永远不会大于堆大小?
答案 0 :(得分:14)
不要写信给ByteArrayOutputStream
。直接写入FileOutputStream
。
String path = "file.txt";
FileOutputStream output = new FileOutputStream(path);
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = inputStream.read(buffer)) != -1) {
output.write(buffer, 0, len);
}
答案 1 :(得分:10)
我接受了建议,跳过ByteArrayOutputStream并写入FileOutputStream,这似乎解决了我的问题。通过一个快速调整,FileOutputStream由BufferedOutputStream
修饰String path = "file.txt";
OutputStream stream = new BufferedOutputStream(new FileOutputStream(path));
int bufferSize = 1024;
byte[] buffer = new byte[bufferSize];
int len = 0;
while ((len = is.read(buffer)) != -1) {
stream.write(buffer, 0, len);
}
if(stream!=null)
stream.close();