【问题标题】:How do I take a ByteArrayInputStream and have its contents saved as a file on the filesystem如何获取 ByteArrayInputStream 并将其内容保存为文件系统上的文件
【发布时间】:2011-02-18 23:04:05
【问题描述】:

我有一个 ByteArrayInputStream 形式的图像。我想把它做成我可以保存到我的文件系统中的某个位置的东西。

我一直在兜圈子,请你帮帮我。

【问题讨论】:

  • 我无法相信这项任务是多么深奥。

标签: java file-io bytearrayinputstream


【解决方案1】:
    ByteArrayInputStream stream  = <<Assign stream>>;
    byte[] bytes = new byte[1024];
    stream.read(bytes);
    BufferedWriter writer = new BufferedWriter(new FileWriter(new File("FileLocation")));
    writer.write(new String(bytes));
    writer.close();

与 FileWriter 相比,Buffered Writer 将提高写入文件的性能。

【讨论】:

  • 写入器用于字符文件,而不是二进制文件
【解决方案2】:

如果您已经在使用 Apache commons-io,您可以这样做:

 IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));

【讨论】:

  • 这很好,但我发现我需要在复制调用之外创建 FileoutputStream 以便我可以关闭它。一些 IOUtils 刷新缓冲区,但我遇到了输出文件有时无法打开的问题。一旦我在 FileOutputStream 上添加了对 close() 的调用,它就工作得很好。总的来说,我很高兴我找到了 IOUtils 的东西,我也一直在用它做其他事情。
【解决方案3】:
InputStream in = //your ByteArrayInputStream here
OutputStream out = new FileOutputStream("filename.jpg");

// Transfer bytes from in to out
byte[] buf = new byte[1024];
int len;
while ((len = in.read(buf)) > 0) {
    out.write(buf, 0, len);
}
in.close();
out.close();

【讨论】:

    【解决方案4】:

    您可以使用以下代码:

    ByteArrayInputStream input = getInputStream();
    FileOutputStream output = new FileOutputStream(outputFilename);
    
    int DEFAULT_BUFFER_SIZE = 1024;
    byte[] buffer = new byte[DEFAULT_BUFFER_SIZE];
    long count = 0;
    int n = 0;
    
    n = input.read(buffer, 0, DEFAULT_BUFFER_SIZE);
    
    while (n >= 0) {
       output.write(buffer, 0, n);
       n = input.read(buffer, 0, DEFAULT_BUFFER_SIZE);
    }
    

    【讨论】:

    • 谢谢 Gaurav,马上试试。
    猜你喜欢
    • 2015-02-05
    • 2015-06-28
    • 1970-01-01
    • 2023-04-10
    • 2018-05-05
    • 2013-08-19
    • 2012-06-14
    • 2010-10-05
    • 2016-11-22
    相关资源
    最近更新 更多