javainputstreamoutputstream

How do I convert an OutputStream to an InputStream?


I am on the stage of development where I have two modules and from one I got output as a OutputStream, and a second one which accepts only InputStream.

Do you know how to convert OutputStream to InputStream (not vice versa, I mean really this way) so that I am able to connect these two parts?


Solution

  • An OutputStream is one where you write data to. If some module exposes an OutputStream, the expectation is that there is something reading at the other end.

    Something that exposes an InputStream, on the other hand, is indicating that you will need to listen to this stream, and there will be data that you can read.

    So it is possible to connect an InputStream to an OutputStream

    InputStream----read---> intermediateBytes[n] ----write----> OutputStream

    As someone metioned, this is what the copy() method from IOUtils lets you do. It does not make sense to go the other way... hopefully this makes some sense

    UPDATE:

    Of course the more I think of this, the more I can see how this actually would be a requirement. I know some of the comments mentioned Piped input/ouput streams, but there is another possibility.

    If the output stream that is exposed is a ByteArrayOutputStream, then you can always get the full contents by calling the toByteArray() method. Then you can create an input stream wrapper by using the ByteArrayInputStream sub-class. These two are pseudo-streams, they both basically just wrap an array of bytes. Using the streams this way, therefore, is technically possible, but to me it is still very strange...