问题
When I save file I use:
File file = new File(filename);
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.
Edit: 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
}
回答1:
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();
Or you can write the contents to another OutputStream:
byteArrayOutputStream.writeTo(System.out);
Or:
file = new File(filename);
fos = new FileOutputStream(file);
byteArrayOutputStream.writeTo(fos);
回答2:
- Please avoid using ByteArrayOutputStream/ByteArrayInputStream, because they are not chunked and creates huge arrays internally
- Please avoid using methods
.toByteArray()
, because they will require additional array allocation - Large allocation is not so optimal than several smaller objects allocations, because the oldest generation will be used. See details in this answer.
What is my recommendation:
- Use
Buffer
class from okio library. It is chunked in memory and support InputStream/OutputStream bindings - Use async way of data read to increase performance. However, I will show synchronous way.
So, short code will be:
Buffer buffer = new Buffer();
buffer.readFrom(previouslyCreatedFileStream); // of course, it is better to use
buffer.writeTo(someOutputStream);
来源:https://stackoverflow.com/questions/37385908/how-to-save-file-in-memory-and-read-file-output-stream