使用以下示例中显示的方法,当其他类拦截输出流时,它会丢失。如何修复我的程序?
控制台.java:
package interception;
import java.awt.BorderLayout;
import java.awt.EventQueue;
import javax.swing.*;
import javax.swing.border.EmptyBorder;
import java.io.*;
public class Console extends JFrame
{
private JPanel contentPane;
private JTextPane textPane;
private class Interceptor extends PrintStream
{
public Interceptor(OutputStream out)
{
super(out,true);
}
@Override
public void print(String s)
{
super.print(s);
textPane.setText(textPane.getText()+s);
}
}
public static void main(String[] args) {
EventQueue.invokeLater(new Runnable() {
public void run()
{
try
{
Console frame = new Console();
frame.setVisible(true);
System.out.print("System standard output stream test\n");
new Troll();
System.out.print("Haters gonna hate\n");
} catch (Exception e) {
e.printStackTrace();
}
}
});
}
public Console()
{
setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
setBounds(100, 100, 450, 300);
contentPane = new JPanel();
contentPane.setBorder(new EmptyBorder(5, 5, 5, 5));
contentPane.setLayout(new BorderLayout(0, 0));
setContentPane(contentPane);
textPane = new JTextPane();
textPane.setEditable(false);
contentPane.add(textPane, BorderLayout.CENTER);
redirectStream();
}
protected void redirectStream()
{
PrintStream iout = new Interceptor(System.out);
System.setOut(iout);
}
}
巨魔.java:
package interception;
import java.io.*;
public class Troll
{
private class Interceptor extends PrintStream
{
public Interceptor(OutputStream out)
{
super(out,true);
}
@Override
public void print(String s)
{
super.print(s);
}
}
public Troll()
{
PrintStream iout = new Interceptor(System.out);
System.setOut(iout);
System.out.print("I've stolen your stream bwahaha!\n");
}
}
换句话说 - 在构建“Troll”之后,控制台不再能够拦截输出流,因此文本“讨厌者会讨厌”不会显示在其中。这就是问题。
更新
关闭Troll
课程流显然是不可接受的解决方案。