Search code examples
arraysresourcesinputstreamtemporary-filesoutputstream

Java Project Modules - use InputStream/OutputStream or .tmpFile/byte[]


I found myself passing InputStream/OutputStream objects around my application modules.

I'm wondering if it's better to
- save the content to disk and pass something like a Resource between the various methods calls
- use a byte[] array
instead of having to deal with streams everytime.

What's your approach in these situations?
Thanks

Edit:
I've a Controller that receives a file uploaded by the user. I've an utility module that provides some functionality to render a file.

utilityMethod(InputStream is, OutputStream os)

The file in InputStream is the one uploaded by the user. os is the stream associated with the response. I'm wondering if it's better to have the utility method to save the generated file in a .tmp file and return the file path, or a byte[], etc. and have the controller to deal with the outputStream directly.


Solution

  • I try to keep as much in RAM as possible (mostly because of performance reasons and RAM is cheap). So I'm using a FileBackedBuffer to "save" data of unknown size. It has a limit. When less than limit bytes are written to it, it will keep them in an internal buffer. If more data is written, I'll create the actual file. This class has methods to get an InputStream and an OutputStream from it, so the using code isn't bothered with the petty details.