redirect OutputStream to an InputStream?
Hello,
I wonder if is possible to redirect an OutputStream to an InputStream...
My idea is to extend FilterOutputStream to write also to a buffer and make the InputStream read it.
I searched around but I can't find any alreay made object that do it.
help!
thanks in advance :)
[315 byte] By [
gandhi_ita] at [2007-10-2 16:10:28]

> I have this similar problem. I have this class I
> downloaded from Internet (jmml) which throws many
> lines of output whenever it does some processing. I
> want to filter some of those lines. So, in order to
> do so, I have to parse them, and the only way I can
> think of is to use the PipedOutputStream or
> PipedInputStream classes, but I'm having some trouble
> using them.
> I'd appreciate any help from you, guys.
Having to guess here... are the "many lines of output" going to System.out? If so there's an easy solution:
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
import java.util.concurrent.Executors;
public class ForumQuestion {
private static PrintStream console = System.out;
private static class CustomFilter implements Runnable {
private BufferedReader reader;
public CustomFilter( InputStream is ) {
reader = new BufferedReader( new InputStreamReader( is ) );
}
public void run() {
try {
String line = reader.readLine();
while( line != null ) {
if ( line.matches( "\\[\\d+\\] Beef" ) ) {
console.println( line );
}
line = reader.readLine();
}
} catch( IOException e ) {
// will I/O exception when end of stream is reached
// and the writing thread is dead
}
}
}
public static void main( String[] args ) throws IOException {
PipedInputStream is = new PipedInputStream();
PipedOutputStream os = new PipedOutputStream( is );
// read from inputstream in a separate thread else the
// outputstream will fill up and block
Executors.newSingleThreadExecutor().execute( new CustomFilter( is ) );
System.setOut( new PrintStream( os ) );
for( int i = 0; i < 100; i++ ) {
if ( i%10 != 0 ) {
System.out.println( String.format( "[%d] Spam%n", i ) );
} else {
System.out.println( String.format( "[%d] Beef%n", i ) );
}
}
}
}