Standard Err and Output Windows : IO redirection « File « Java Tutorial






import java.io.OutputStream;
import java.io.PrintStream;

import javax.swing.JFrame;
import javax.swing.JScrollPane;
import javax.swing.JTextArea;
import javax.swing.ScrollPaneConstants;

public class StdErrOutWindows {
  JTextArea outArea = new JTextArea(20, 50), errArea = new JTextArea(20, 50);;

  public StdErrOutWindows() {
    JScrollPane pain = new JScrollPane(outArea);
    JFrame outFrame = new JFrame("out");
    outFrame.getContentPane().add(pain);
    outFrame.setVisible(true);
    
    pain = new JScrollPane(errArea);
    JFrame errFrame = new JFrame("err");
    errFrame.getContentPane().add(pain);
    errFrame.setLocation(errFrame.getLocation().x + 20, errFrame.getLocation().y + 20);
    errFrame.setVisible(true);

    System.setOut(new PrintStream(new JTextAreaOutputStream(outArea)));
    System.setErr(new PrintStream(new JTextAreaOutputStream(errArea)));
  }

  public static void main(String[] args) {
    new StdErrOutWindows();
    System.out.println("test to out");
    try {
      throw new Exception("Test exception");
    } catch (Exception e) {
      e.printStackTrace();
    }
  }

  public class JTextAreaOutputStream extends OutputStream {
    JTextArea ta;

    public JTextAreaOutputStream(JTextArea t) {
      super();
      ta = t;
    }

    public void write(int i) {
      ta.append(Character.toString((char)i));
    }

    public void write(char[] buf, int off, int len) {
      String s = new String(buf, off, len);
      ta.append(s);
    }

  }

}








11.70.IO redirection
11.70.1.Redirect standard error
11.70.2.Redirect standard output
11.70.3.Redirecting Standard Output, and Error
11.70.4.Replace standard output and error with a print stream, output to both the console and to a file.
11.70.5.Standard Err and Output Windows
11.70.6.Redirect standard output to a file
11.70.7.Demonstrates standard I/O redirection