【问题标题】:How to write a potentially huge InputStream to File?如何将潜在的巨大 InputStream 写入文件?
【发布时间】:2012-04-12 05:36:48
【问题描述】:

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

【问题讨论】:

  • 你说我的担心无关紧要?
  • 只要去掉ByteArrayOutputStream。 (我读错了..我用它吗?)

标签: android inputstream fileoutputstream


【解决方案1】:

不要写信给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);
}

【讨论】:

  • 嗯,我想这是有道理的。
  • 我选择了这个 OutputStream output = new BufferedOutputStream(new FileOutputStream(path));阅读 FileOutputStream 文档后。
  • 随时编辑我的答案以反映这一点,并接受它。否则,您可以/应该发布并接受您自己的答案。
【解决方案2】:

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

【讨论】:

  • 不是 is 应该是 FileInputStream 吗?未定义
  • 使用 BufferedOutputStream 而不是直接使用 FileOutputStream 有什么好处?
猜你喜欢
  • 2014-03-31
  • 2016-03-19
  • 1970-01-01
  • 2016-12-22
  • 1970-01-01
  • 1970-01-01
  • 2013-09-21
  • 2013-09-14
  • 1970-01-01
相关资源
最近更新 更多