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

Comments

Subscribe
Notify of
guest
3 Comments
Most Voted
Newest Oldest
Inline Feedbacks
View all comments

About Us

HowToDoInJava provides tutorials and how-to guides on Java and related technologies.

It also shares the best practices, algorithms & solutions and frequently asked interview questions.

Our Blogs

REST API Tutorial

Dark Mode

Dark Mode