开发者

How to create a file that streams to http response

I'm writing a web application and want the user to be able click a link and get a file download.

I have an interface is in a third party library that I can't alter:

writeFancyData(File file, Data开发者_运维问答 data);

Is there an easy way that I can create a file object that I can pass to this method that when written to will stream to the HTTP response?

Notes:

Obviously I could just write a temporary file and then read it back in and then write it the output stream of the http response. However what I'm looking for is a way to avoid the file system IO. Ideally by creating a fake file that when written to will instead write to the output stream of the http response.

e.g.

writeFancyData(new OutputStreamBackedFile(response.getOutputStream()), data);

I need to use the writeFancyData method as it writes a file in a very specific format that I can't reproduce.


Assuming writeFancyData is a black box, it's not possible. As a thought experiment, consider an implementation of writeFancyData that did something like this:

public void writeFancyData(File file, Data data){
    File localFile = new File(file.getPath());
    ... 
    // process data from file
    ...
}

Given the only thing you can return from any extended version of File is the path name, you're just not going to be able to get the data you want into that method. If the signature included some sort of stream, you would be in a lot better position, but since all you can pass in is a File, this can't be done.

In practice the implementation is probably one of the FileInputStream or FileReader classes that use the File object really just for the name and then call out to native methods to get a file descriptor and handle the actual i/o.


As dlawrence writes the API it is impossible to determine what the API is doing with the File.

A non-java approach is to create a named pipe. You could establish a reader for the pipe in your program, create a File on that path and pass it to API.

Before doing anything so fancy, I would recommend analyzing performance and verify that disk i/o is indeed a bottleneck.


Given that API, the best you can do is to give it the File for a file in a RAM disk filesystem.

And lodge a bug / defect report against the API asking for an overload that takes a Writer or OutputStream argument.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜