I have a piece of code like this:
我有一段这样的代码:
System.setOut(new PrintStream(new OutputStream()
{
@Override
public void write(int b) throws IOException
{
String str = String.valueOf((char) b);
txtAreaConsole.appendText(str);
}
}));
But that means, I don't get any information in the console anymore. So I'm looking for something like this:
但这意味着,我不再在控制台中获得任何信息。所以我正在寻找这样的东西:
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
}
}));
Is there anything like that? Thanks
有什么相似的吗?谢谢
2 个解决方案
#1
1
Sure you can, you just need to "save" and reuse the existing System.out.
当然可以,你只需要“保存”并重用现有的System.out。
I don't know what txtAreaConsole is in you code, so I just made a "MyConsole" in the following example:
我不知道你的代码中有什么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();
}
}
#2
0
TeeOutputStream from Apache Commons IO was, as Andreas suggested, the best way for me.
正如安德烈亚斯建议的那样,来自Apache Commons IO的TeeOutputStream对我来说是最好的方式。
#1
1
Sure you can, you just need to "save" and reuse the existing System.out.
当然可以,你只需要“保存”并重用现有的System.out。
I don't know what txtAreaConsole is in you code, so I just made a "MyConsole" in the following example:
我不知道你的代码中有什么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();
}
}
#2
0
TeeOutputStream from Apache Commons IO was, as Andreas suggested, the best way for me.
正如安德烈亚斯建议的那样,来自Apache Commons IO的TeeOutputStream对我来说是最好的方式。