I am on the stage of development, where I have two modules and from one I got output as a OutputStream
and second one, which accepts only InputStream
. Do you know how to convert OutputStream
to InputStream
(not vice versa, I mean really this way) that I will be able to connect these two parts?
Thanks
Best Answer
There seem to be many links and other such stuff, but no actual code using pipes. The advantage of using
java.io.PipedInputStream
andjava.io.PipedOutputStream
is that there is no additional consumption of memory.ByteArrayOutputStream.toByteArray()
returns a copy of the original buffer, so that means that whatever you have in memory, you now have two copies of it. Then writing to anInputStream
means you now have three copies of the data.The code:
This code assumes that the
originalByteArrayOutputStream
is aByteArrayOutputStream
as it is usually the only usable output stream, unless you're writing to a file. I hope this helps! The great thing about this is that since it's in a separate thread, it also is working in parallel, so whatever is consuming your input stream will be streaming out of your old output stream too. That is beneficial because the buffer can remain smaller and you'll have less latency and less memory usage.