Reputation: 789
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.
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:
Upvotes: 0
Views: 9820
Reputation: 789
To answer my own question, yes you can build a redirect like this:
class OutInInputRedirect {
public final transient InputStream is;
public final transient OutputStream os;
public OutInInputRedirect() throws IOException {
this(1024);
}
public OutInInputRedirect(int size) throws IOException {
PipedInputStream is = new PipedInputStream(size);
PipedOutputStream os = new PipedOutputStream(is);
this.is = is;
this.os = os;
}
}
Just use the OutputStream
as an replacement and the InputStream
in those places you need, be awere that the closing of the OutputStream
also closes the InputStream
!
It is quite easy and works as expected. Either way you cannot change an already connected stream (without reflection).
Upvotes: 1
Reputation: 86744
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.
Upvotes: 1