[英]How to make Redirect.INHERIT and System.setOut work together
[英]How can I redirect the System.out.println() of constructor of superclass to System.setOut() of subclass?
在超类的构造函数中有一些多个 System.out.println(),我必须使用 System.setOut(ps) 将它们重定向到 PrintStream object ps。
例如,如果我有这样的超类:
import java.awt.GridLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import javax.swing.JFrame;
public class SuperClass implements ActionListener{
public SuperClass(){
System.out.println("Some message");
}
public String toString(){
return "Some other message";
}
@Override
public void actionPerformed(ActionEvent event)
{
System.out.println(toString());
}
}
和这样的子类:
import java.io.IOException;
import java.io.PrintStream;
public class SubClass extends SuperClass{
private PrintStream ps;
public SubClass(){
super();
try {
ps = new PrintStream("file.txt");
} catch (IOException e){
e.getStackTrace();
}
System.setOut(ps);
}
}
每当执行操作时(例如,按下超类中的 JFrame 按钮),actionPerformed() 中的 System.out.println() 将重定向到 PrintStream object,但构造函数中的 System.out.println() 不会。
另外,如何将 System.out 重定向到 PrintStream object 并保留 System.out? (即同时打印 System.out 和 PrintStream)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.