我有一段这样的代码:
System.setOut(new PrintStream(new OutputStream()
{
@Override
public void write(int b) throws IOException
{
String str = String.valueOf((char) b);
txtAreaConsole.appendText(str);
}
}));
但这意味着,我不再在控制台中获得任何信息。所以我要找这样的东西:
System.setOut(new PrintStream(new OutputStream()
{
@Override
public void write(int b) throws IOException
{
String str = String.valueOf((char) b);
txtAreaConsole.appendText(str);
defaultConsole.appendText(str); //THIS
}
}));
有这样的东西吗?由于
当然可以,你只需要"保存"并重用现有的System.out。
我不知道txtAreaConsole是什么在你的代码,所以我只是做了一个"MyConsole"在下面的例子:
import java.io.PrintStream;
import java.text.*;
public class Test {
public Test() {
System.setOut(new MySystemOut(System.out, new MyConsole()));
System.out.println("Hey");
}
class MyConsole {
public void appendText(String s) {
// write text somewhere else here
}
}
class MySystemOut extends PrintStream {
private final PrintStream out;
private final MyConsole txtAreaConsole;
public MySystemOut(PrintStream out, MyConsole txtAreaConsole) {
super(out);
this.out = out;
this.txtAreaConsole = txtAreaConsole;
}
@Override
public void write(int b) {
String str = String.valueOf((char) b);
txtAreaConsole.appendText(str);
out.write(b);
}
}
public static void main(String args[]) throws ParseException {
new Test();
}
}
来自Apache Commons IO的TeeOutputStream,正如Andreas所建议的,对我来说是最好的方式。