Capture System.out into a JFrame : FilterOutputStream « File « Java Tutorial






import java.io.ByteArrayOutputStream;
import java.io.FileWriter;
import java.io.FilterOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.io.PrintStream;

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

public class Main extends JFrame {
  JTextArea aTextArea = new JTextArea();
  PrintStream aPrintStream = new PrintStream(new FilteredStream(new ByteArrayOutputStream()));

  public Main() {
    setSize(300, 300);
    add("Center", new JScrollPane(aTextArea));
    setVisible(true);

    System.setOut(aPrintStream); // catches System.out messages
    System.setErr(aPrintStream); // catches error messages
  }

  class FilteredStream extends FilterOutputStream {
    public FilteredStream(OutputStream aStream) {
      super(aStream);
    }

    public void write(byte b[]) throws IOException {
      String aString = new String(b);
      aTextArea.append(aString);
    }

    public void write(byte b[], int off, int len) throws IOException {
      String aString = new String(b, off, len);
      aTextArea.append(aString);
      FileWriter aWriter = new FileWriter("a.log", true);
      aWriter.write(aString);
      aWriter.close();
    }
  }
}








11.21.FilterOutputStream
11.21.1.extends FilterOutputStream for printable characters
11.21.2.Capture System.out into a JFrame
11.21.3.extends FilterOutputStream
11.21.4.Count the number of bytes written to the output stream.
11.21.5.Rollover FileOutputStream
11.21.6.Provide a debug trace of the stuff thats being written out into the DataOutputStream
11.21.7.Adds extra dot if dot occurs in message body at beginning of line (according to RFC1939)
11.21.8.Apply a ASCII Hex encoding to the stream