Search code examples
javainputstreamoutputstream

converting OutputStream into an InputStream


Is there any way to convert an OutputStream into an InputStream?

So the following would work

InputStream convertOStoIS(OutputStream os) {

}

I do not want to use any libraries, I read that there are some who are able to accomplish this with bytecode manipulation.

Edit

I want to be able to intersect a sink, to analyze the data or redirect the output. I want to place another OutputStream under the on given by some function and redirect the data into another input stream.

The related topics had a ByteArrayOutputStream or a PipedStream which is not the case in my question.

Related:


Solution

  • Use a java.io.FilterOutputStream to wrap the existing OutputStream. By overriding the write() method you can intercept output and do whatever you want with it, either send it somewhere else, modify it, or discard it completely.

    As to your second question, you cannot change the sink of an OutputStream after the fact, i.e. cause previously written data to "move" somewhere else, but using a FilterOutputStream you can intercept and redirect any data written after you wrap the original `OutputStream.