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

E.g.

//OutputStream
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
inputChannel.close();
fis.close();

outputChannel.close();
fos.close();

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+ Fellow Programmers

Subscribe to get new post notifications, industry updates, best practices, and much more. Directly into your inbox, for free.

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

    Reply

Leave a Comment

HowToDoInJava

A blog about Java and its related technologies, the best practices, algorithms, interview questions, scripting languages, and Python.