12

我有一个返回字节数组的 API 调用。我目前将结果流式传输到一个字节数组中,然后确保校验和匹配,然后将 ByteArrayOutputStream 写入文件。代码是这样的,它工作得很好。

    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 分块写入文件的最优雅方法是什么,这样字节数组永远不会大于堆大小?

4

2 回答 2

15

不要写信给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);
}
于 2012-03-28T15:25:12.967 回答
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();
于 2012-03-28T19:36:10.953 回答