首页 文章

如何写一个潜在的巨大InputStream到文件?

提问于
浏览
11

我有一个返回字节数组的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 回答

  • 10

    不要写入 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);
    }
    
  • 14

    我接受了建议跳过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();
    

相关问题