There are some multiple System.out.println() in the constructor of the superclass, and I have to redirect them to PrintStream object ps using System.setOut(ps).
for example, if I have a superclass like this:
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());
}
}
and a subclass like this:
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);
}
}
whenever the action is performed (ex. pressing a JFrame Button from superclass), the System.out.println() from actionPerformed() is redirected to PrintStream object, but the System.out.println() from the constructor is not.
Also, how can I redirect the System.out to PrintStream object AND keep the System.out? (i.e. printing both System.out and PrintStream)
CodePudding user response:
- The problem is in constructors order.
Shortly when you call
SubClass
constructor it callsSuperClass
first, because you have to init parent first.( When you call subclass constructor, it always call parent constructor first). This question have answer about init order. - To add info for file and console adding logger can fit your aims. You can configure it in several ways. Link If you want to write without logger, just to file and console, take a look for this question