Posts

Showing posts from July, 2022

How to Convert OutputStream to InputStream

Sometime we need to convert Output Stream to Input Stream. We can perform the conversion multiple ways.  The following two approaches are most popular: 1. ByteArrayOutputStream to ByteArrayInputStream 2. PipedOutputStream to PipedInputStream Complete example code is available in the [ Github ]. Approach 1: ByteArrayOutputStream/ByteArrayInputStream The ByteArrayOutputStream/ByteArrayInputStream is the easiest way to convert OutputStream to InputStream. Code snippet: TextWriter textWriterBins = new TextWriter(); ByteArrayOutputStream bouts = new ByteArrayOutputStream(); textWriterBins.write(bouts); ByteArrayInputStream bins = new ByteArrayInputStream(bouts.toByteArray()); TextReader textReader = new TextReader(bins); textReader.print(); Here, TextWriter is a class which writes some text in the OutputStream and TextReader is a class which reads data from InputStream and print on the console. In the above code snippet, the TextWriter.write method writes the da...