How to save file in memory and read file output stream?

亡梦爱人 提交于 2019-12-23 04:47:13

问题


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:


  1. Please avoid using ByteArrayOutputStream/ByteArrayInputStream, because they are not chunked and creates huge arrays internally
  2. Please avoid using methods .toByteArray(), because they will require additional array allocation
  3. 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:

  1. Use Buffer class from okio library. It is chunked in memory and support InputStream/OutputStream bindings
  2. 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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!