Java 如何获取 ByteArrayInputStream 并将其内容保存为文件系统上的文件
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2824674/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How do I take a ByteArrayInputStream and have its contents saved as a file on the filesystem
提问by Ankur
I have an image which is in the form of a ByteArrayInputStream. I want to take this and make it something that I can save to a location in my filesystem.
我有一个 ByteArrayInputStream 形式的图像。我想把它做成可以保存到文件系统中某个位置的东西。
I've been going around in circles, could you please help me out.
我一直在绕圈子,你能帮我吗?
采纳答案by Simon Nickerson
If you are already using Apache commons-io, you can do it with:
如果您已经在使用 Apache commons-io,您可以使用:
IOUtils.copy(byteArrayInputStream, new FileOutputStream(outputFileName));
回答by Gaurav Vaish
You can use the following code:
您可以使用以下代码:
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);
}
回答by maneesh
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();
回答by Phani
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();
Buffered Writer will improve performance in writing files compared to FileWriter.
与 FileWriter 相比,Buffered Writer 将提高写入文件的性能。