Java Convert OutputStream to InputStream Example

In this Java example, we will learn to convert OutputStream to InputStream which we may need when we read data from one source which return an outputstream; and write/pass the data to other target which wants data in inputstream.

1. Convert OutputStream to InputStream using byte array

Here, we will utilize byte array to pass intermediate data.

OutputStream -> byte[] -> InputStream


ByteArrayOutputStream outStream = new ByteArrayOutputStream(new File(outputFile));

//byte[] -> InputStream
ByteArrayInputStream inStream = new ByteArrayInputStream( outStream.toByteArray() )

This is the simplest way to convert from OutputStream to InputStream in java.

2. Copy OutputStream to InputStream Using NIO Channels

Above approach is pretty much useful when you have limited data in OutputStream. If you have some big amount of data, then you want to do the conversion in realtime in form of stream where whole data is not stored in buffer – at any amount of time.

In other words, you will need to create a pipe approach where data is flowing from one end to other end – and no need to store complete data in buffer.

FileOutputStream fos = new FileOutputStream(new File(outputFile));
FileChannel outputChannel = fos.getChannel();

FileInputStream fis = new FileInputStream(inputFile);
FileChannel inputChannel = fis.getChannel();

//Transfer from output stream to input stream is happening here
outputChannel.transferTo(0, inputChannel.size(), inputChannel);

/Don't forget to close the streams and channels


Read More: Java NIO – Data Transfer between Channels

That’s all. If you have more effective and practical ways to convert outputstream to inputstream in java, please share with us.

Happy Learning !!

Was this post helpful?

Join 7000+ Awesome Developers

Get the latest updates from industry, awesome resources, blog updates and much more.

* We do not spam !!

3 thoughts on “Java Convert OutputStream to InputStream Example”

  1. this article title’s “Convert OutputStream to InputStream using byte array”, but in fact what is being shown is how to convert a FileOutputStream (a subtype of OutputStream); I wanted to get know it with an OutputStream itself


Leave a Comment


A blog about Java and related technologies, the best practices, algorithms, and interview questions.