Convert OutputStream to InputStream in Java - Example

While writing some posts in this blog, I had to stumble across this problem - how to convert OutputStream to InputStream in Java? I tried scanning through Java docs; Apache Common IO utilities, all in vain. There is a method in that takes an input stream and converts it to an output stream. But that is not I want. I want the other way. I'd to do this because at times I write a JFreeChart chart object to output stream and I want that to be consumed into an Input Stream for some other purposes. After much scanning and googling, I found a nice post that explained how to do this..(with different options too)

With due credits to the original post, I would like to produce the original ByteArrayOutputStream method example, that I utilized in one of my blog posts earlier.  The code snippet that converts an OutputStream to InputStream is provided below:
                /* We don't want to create an intermediate file. So, we create a byte array output stream 
                and byte array input stream
                And we pass the chart data directly to input stream through this */             
                /* Write chart as PNG to Output Stream */
                ByteArrayOutputStream chart_out = new ByteArrayOutputStream();          
                /* We can now read the byte data from output stream and stamp the chart to Excel worksheet */
                int my_picture_id = my_workbook.addPicture(chart_out.toByteArray(), Workbook.PICTURE_TYPE_PNG);

Here are the steps that is followed in that blog to convert Output Stream to Input Stream.

  • Create a ByteArrayOutputStream object first. (Highlighted in yellow)
  • Write the data you want to the output stream, created earlier. (Highlighted in blue)
  • Now, you can use ByteArrayOutputStream.toByteArray() to convert Output Stream to a byte array. (Pink)
  • Equivalently, you can convert ByteArrayOutputStream to ByteArrayInputStream by using toByteArray() method.
I found this approach very elegant and easy to perform the conversion between these streams. Wish Apache adds this to the Commons IO library soon, so that it can be easily accessed.

The original post describes some other methods to perform this also. (Pipes / Circular Buffers). You can give it a read, if you want to , or looking for more options to perform this conversion.

1 comment:

  1. Hi, i have been digging into this problem for some time now... 4 years ago i wrote an open source library (called EasyStream) to ease the task of passing from OutputStream to InputStream.
    Here you can find an explanation of the problem, and the possible ways to solve it.
    If you have large quantity of data (that was my case) the best way is to use pipes, but it's quite complicated because they require a new thread. So i tried to hide everything under a nice interface, and this is the result.