如何将文件保存在内存中并读取文件输出流? [英] How to save file in memory and read file output stream?
本文介绍了如何将文件保存在内存中并读取文件输出流?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
保存文件时,我使用:
File file = new File(filename);
但是,由于我不再具有写文件夹的权限,我想将其保存到内存中,然后再将文件读取到FileOutputStream.
But, since I no longer have privileges to write to folders, I would like rather to save it to memory and then read file to FileOutputStream.
我已经读过我可以用这种方法将文件保存到内存中
I have read I can save file to memory with this approach:
new ByteArrayOutputStream();
整个代码看起来如何?上传完成后,我无法弄清楚如何正确编写它.
How would whole code look like? I can't figure it out how to write it properly after upload is done.
我正在使用Vaadins上传插件:
I'm using Vaadins upload plugin:
public File file;
public OutputStream receiveUpload(String filename,
String mimeType) {
// Create upload stream
FileOutputStream fos = null; // Stream to write to
file = null;
if(StringUtils.containsIgnoreCase(filename, ".csv")){
try {
file = new File(filename);
fos = new FileOutputStream(file);
} catch (final java.io.FileNotFoundException e) {
new Notification("Error", e.getMessage(), Notification.Type.WARNING_MESSAGE)
.show(Page.getCurrent());
return null;
}
} else {
new Notification("Document is not .csv file", Notification.Type.WARNING_MESSAGE)
.show(Page.getCurrent());
return null;
}
return fos; // Return the output stream to write to
}
推荐答案
public OutputStream receiveUpload(String filename,
String mimeType) {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
return byteArrayOutputStream;
}
您可以使用以下方法将内容写入流中:
You can get the content written in the stream using:
byte[] dataWrittenInTheOutputStream = byteArrayOutputStream.toByteArray();
或者您可以将内容写入另一个OutputStream:
Or you can write the contents to another OutputStream:
byteArrayOutputStream.writeTo(System.out);
或者:
file = new File(filename);
fos = new FileOutputStream(file);
byteArrayOutputStream.writeTo(fos);
这篇关于如何将文件保存在内存中并读取文件输出流?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文