How to Convert OutputStream to InputStream in Java

In this Java tutorial, we will see how to convert an OutputStream to InputStream.

To achieve this, we read data from one source return the output stream; and write/pass the data to another stream that wants data in the input stream.

Table of Content :



What is an OutputStream?

An OutputStream is one where you write data and someone reads it at the other end.

What is an InputStream?

InputStream class, java.io.InputStream, represents an ordered stream of bytes. Means can read data from a Java InputStream as an ordered sequence of bytes. This is useful when reading data from a file, or received over the network.

Difference between OutputStream and InputStream

OutputStream InputStream
OutputStream Write Data to the destination once at a time InputStream Read data from the source once at a time.
It is an abstract class that describes Stream Output. It is an abstract class that describes Stream Input
Types of OutputStream are: FileOutputStream, ByteArrayOutputStream, FilterOutputStream and ObjectOutputStream Types of InputStream are: FileInputStream ByteArrayInputStream FilterInputStream and ObjectInputStream
the most important and mostly used type is FileInputStream the most important and mostly used type is FileInputStream

The flow is like that

InputStream --- read --> intermediateBytes[n] ---write ----> OutputStream

Convert OutputStream to InputStream in Java

If the output stream that is exposed is a ByteArrayOutputStream, then you can always get the full contents by calling the toByteArray() method. Then you can create an input stream wrapper by using the ByteArrayInputStream sub-class.

Convert OutputStream to InputStream

There are 3 ways to convert OutputStream to InputStream. We will see them one by one.

1) Using byte array

A ByteArrayInputStream contains an internal buffer that contains bytes that may be read from the stream. An internal counter keeps track of the next byte to be supplied by the read method.
Closing a ByteArrayInputStream has no effect. The methods in this class can be called after the stream has been closed without generating an IOException.

//Convert file to byte ByteArrayOutputStream File file = new File("abc.txt"); ByteArrayOutputStream outStream = new ByteArrayOutputStream(file); //Convert byte array to InputStream ByteArrayInputStream inStream = new ByteArrayInputStream( outStream.toByteArray() //intermediate class which will serve a buffer between OutputStream and InputStream ByteArrayOutputStream buffer = (ByteArrayOutputStream) aOutputStream; byte[] bytes = buffer.toByteArray(); InputStream inputStream = new ByteArrayInputStream(bytes);

Limitations:

ByteArrayOutputStream.toByteArray() returns a copy of the original buffer, so that means that whatever you have in memory, you now have two copies of it.
Then writing to an InputStream means you now have three copies of the data.

2). Using pipes

A piped input stream should be connected to a piped output stream; the piped input stream then provides whatever data bytes are written to the piped output stream

PipedInputStream pipedInputStream = new PipedInputStream();
PipedOutputStream pipedOutputStream = new PipedOutputStream(pipedInputStream );
new Thread( new Runnable(){ public void run(){ class1.putDataOnOutputStream(pipedOutputStream);
} } ).start(); class2.processDataFromInputStream(pipedInputStream);

We can use lambdas code for the same

PipedInputStream in = new PipedInputStream(); final PipedOutputStream out = new PipedOutputStream(in); // in a background thread, write the given output stream to the // PipedOutputStream for consumption ((Runnable)() -> {originalByteArrayOutputStream.writeTo(out);}).run();

If you are getting the ClosedPipeException, then we can use try-with-resources.

// create a copy of the stream and re-write it to an InputStream PipedInputStream in = new PipedInputStream(); new Thread(new Runnable() { public void run () { // if we use the try block outside the Thread will cause the PipedOutputStream resource to close before the Runnable finishes try (final PipedOutputStream out = new PipedOutputStream(in)) { // write the original OutputStream to the PipedOutputStream // try-with-resources here // to work below method ,we need to ensure that the data has finished writing to the ByteArrayOutputStream originalByteArrayOutputStream.writeTo(out); } catch (IOException e) { // logging and exception handling should go here } } }).start();

Advantage:

The advantage of using java.io.PipedInputStream and java.io.PipedOutputStream is that there is no additional consumption of memory.

3). Using NIO Channels

In this approach, we have to create a pipe where data is flowing from one end to the other end, and no need to store complete data in the buffer. We are using FileChannel class.
FileChannel class is used for reading, writing, mapping, and manipulating a file.

FileOutputStream fileOutputStream = new FileOutputStream(new File(outputFile)); FileChannel outputChannel = fileOutputStream.getChannel(); FileInputStream fileInputStream = new FileInputStream(inputFile); FileChannel inputChannel = fileInputStream.getChannel(); outputChannel.transferTo(0, inputChannel.size(), inputChannel); inputChannel.close(); fileOutputStream.close(); outputChannel.close(); fileOutputStream.close();

Post/Questions related to  Convert OutputStream to InputStream in Java

Read file to byte[] array in Java How to convert the input stream to byte array in java?
Create New File in Java
How to convert byte array to input stream in java?
Which of the below stream is used to write data to any destination byte by byte?
How do you create an InputStream from a byte array?
How to Convert OutputStream to InputStream in Java

In this article, we have seen What is an OutputStream and various ways to convert OutputStream to InputStream in Java.