Note that there are some explanatory texts on larger screens.

plurals
  1. POMulti-way redirection of System.out
    primarykey
    data
    text
    <p>With approach shown in the following example, the output stream is being lost when an other class intercepts it. How to fix my program?</p> <p>Console.java:</p> <pre><code>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); } } </code></pre> <p>Troll.java:</p> <pre><code>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"); } } </code></pre> <p><img src="https://i.stack.imgur.com/W6N11.png" alt="enter image description here"></p> <p>In other words - after construction of "Troll" the Console is no longer able to intercept the output stream, so the text "haters gonna hate" isn't shown inside it. This is the problem.</p> <p><strong>UPDATE</strong></p> <p>Closing stream for <code>Troll</code> class is obviously unacceptable solution.</p>
    singulars
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload