muss nicht unbedingt ein PipedOutputStream sein... System (Java Platform SE 6)) erlaubt jeglichen PrintStream.
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PipedInputStream;
import java.io.PipedOutputStream;
import java.io.PrintStream;
public class PipedTest
{
public PipedInputStream pin;
public PipedOutputStream pout;
private IHandler handler;
private boolean run;
public PipedTest(IHandler handler) throws IOException
{
run = true;
pout= new PipedOutputStream();
pin = new PipedInputStream(pout);
this.handler = handler;
System.setOut(new PrintStream( pout ));
start();
}
public void start()
{
new Thread()
{
public void run()
{
while(run)
{
try
{
BufferedReader reader = new BufferedReader( new InputStreamReader( pin ));
String out = "";
while(reader.ready())
{
out = reader.readLine();
if(out.trim().length() > 0)
handler.handleInput(out);
}
}
catch(IOException e)
{
e.printStackTrace();
}
}
};
}.start();
}
public void kill()
{
run = false;
}
public static void main(String[] args)
{
IHandler h = new IHandler()
{
@Override
public void handleInput(String rslt)
{
System.err.println("INPUT: " + rslt);
}
};
try
{
PipedTest pipe = new PipedTest(h);
System.out.println("Hallo");
System.out.println("du");
System.out.println("da");
pipe.kill();
}
catch (IOException e)
{
e.printStackTrace();
}
}
}
interface IHandler
{
public void handleInput(String rslt);
}
INPUT: Hallo
INPUT: du
INPUT: da
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;
import javax.swing.JOptionPane;
public class OSGS
extends OutputStream
{
private boolean read = false;
private String out = null;
@Override
public void write(int b) throws IOException
{
if(read)
out += (char) b;
}
@Override
public synchronized void write(byte[] b, int off, int len) throws IOException
{
read = !read;
// Experimentell(!) in den Test funktioniert das
if(read)
out = "";
else
notifyAll();
super.write(b, off, len);
}
public synchronized String getSystemOut() throws InterruptedException
{
while(out == null)
{
wait();
}
String rslt = out;
out = null;
return rslt;
}
public static void main(String[] args)
{
final OSGS osgs = new OSGS();
System.setOut( new PrintStream( osgs ) );
Thread receiver = new Thread()
{
public void run()
{
boolean run = true;
while(run)
{
try
{
String str = osgs.getSystemOut();
System.err.println("Received: " + str);
}
catch (InterruptedException e)
{
run = false;
}
}
};
};
receiver.start();
for(int i=0; i<3; i++)
{
String get = JOptionPane.showInputDialog("Message:");
System.out.println(get);
}
receiver.interrupt();
}
}