Converting OutputStream to InputStream

In this Java tutorial, we will learn to convert an OutputStream to InputStream that we may need when we read data from one source returning the output stream; and writing/passing the data to another target that wants data in the input stream.

1. Using ByteArrayInputStream

ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. We can read the bytes from an input stream and store them in its internal buffer. Later an application can use the bytes stored in the ByteArrayInputStream as input stream.

Here, we will utilize a byte array to store and transfer the intermediate data. The flow will be:

OutputStream -> byte[] -> InputStream

In the given example, we are creating an output stream from a file for demo purposes. Then we pass the bytes from the file to the input stream.

//OutputStream
ByteArrayOutputStream outStream = new ByteArrayOutputStream(new File("path/file"));

//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

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

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

try(FileOutputStream fos = new FileOutputStream(new File("path/out/file"));
FileInputStream fis = new FileInputStream(new File("path/in/file"));) {
	
	FileChannel outputChannel = fos.getChannel();
	FileChannel inputChannel = fis.getChannel();

	outputChannel.transferTo(0, inputChannel.size(), inputChannel);
}

Read More: Java NIO – Data Transfer between Channels

That’s all. If you have more effective and practical ways to convert output stream to input stream 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 “Converting OutputStream to InputStream”

  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 related technologies, the best practices, algorithms, and interview questions.