In this java example, we will learn to convert OutputStream to InputStream which you may need when you 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
//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 !!