1 import java.io.*;
2 import java.awt.*;
3 import java.awt.event.*;
4 import javax.swing.*;
5 import javax.swing.text.*;
6
7 public class ConsoleOutputStream extends OutputStream {
8 private Document document = null;
9 private ByteArrayOutputStream outputStream = new ByteArrayOutputStream(256);
10 private PrintStream ps = null;
11
12 public ConsoleOutputStream(Document document, PrintStream ps) {
13 this.document = document;
14 this.ps = ps;
15 }
16
17 public void write(int b) {
18 outputStream.write(b);
19 }
20
21 public void flush() throws IOException {
22 super.flush();
23
24 try {
25 if (document != null) {
26 document.insertString(document.getLength(),
27 new String(outputStream.toByteArray()), null);
28 }
29
30 if (ps != null) {
31 ps.write(outputStream.toByteArray());
32 }
33
34 outputStream.reset();
35 }
36 catch(Exception e) {}
37 }
38
39 public static void main(String[] args) {
40 JTextArea textArea = new JTextArea();
41 JScrollPane scrollPane = new JScrollPane(textArea);
42
43 JFrame frame = new JFrame("Redirect Output");
44 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
45 frame.getContentPane().add(scrollPane);
46 frame.setSize(300, 600);
47 frame.setVisible(true);
48
49 System.setOut(new PrintStream(
50 new ConsoleOutputStream(textArea.getDocument(), System.out), true));
51 System.setErr(new PrintStream(
52 new ConsoleOutputStream(textArea.getDocument(), null), true));
53
54 Timer timer = new Timer(1000, new ActionListener() {
55 public void actionPerformed(ActionEvent e) {
56 System.out.println(new java.util.Date().toString());
57 System.err.println(System.currentTimeMillis());
58 }
59 });
60 timer.start();
61 }
62 }
참고: http://forum.java.sun.com/thread.jspa?threadID=651878&messageID=3843547
