Redirecting System.out to a JTextArea

I was recently working on a small Demo UI for a Metro web service client. Creating the UI was fairly simple, but I was thinking that it would be nice to show the raw SOAP messages in the UI. Getting Metro to output the SOAP messages was easy, but the Metro was outputting them to System.out. I thought, “Surely there must be a way to redirect System.out to a JTextArea. After all, if Eclipse can do it, then so can I!” So here’s what I came up with. 

public class TextAreaOutputStream extends OutputStream
{
    private static int BUFFER_SIZE = 8192;
    private JTextArea target;
    private byte[] buffer = new byte[BUFFER_SIZE];
    private int pos = 0;

    public TextAreaOutputStream(JTextArea target)
    {
        this.target = target;
    }

    @Override
    public void write(int b) throws IOException
    {
        buffer[pos++] = (byte)b;
        //Append to the TextArea when the buffer is full
        if (pos == BUFFER_SIZE) {
            flush();
        }
    }

    @Override
    public void flush() throws IOException
    {
        byte[] flush = null;
        if (pos != BUFFER_SIZE) {
            flush = new byte[pos];
            System.arraycopy(buffer, 0, flush, 0, pos);
        }
        else {
            flush = buffer;
        }

        target.append(new String(flush));
        pos = 0;
    }
}

As you can see, this is a very simple buffered OuptutStream that writes to a JTextArea when the buffer is full. Well, that handles writing to a JTextArea, but how about redirecting System.out?

JTextArea consoleText = new JTextArea();
TextAreaOutputStream textOut = new TextAreaOutputStream(consoleText);
PrintStream outStream = new PrintStream(textOut, true);
System.setOut(outStream);

Note the PrintStream constructor I used. The second argument is the “autoFlush” argument. Setting this to true means that whenever the PrintStream encounters a newline, it will flush the OutputStream (which appends to the JTextArea).

And there you have it. Now anything that calls System.out.println will now end up printing directly to your JTextArea.

5 thoughts on “Redirecting System.out to a JTextArea

  1. Zhelyan says:

    Extremely fast, well done

  2. Emmanuel says:

    how do i implement your codes into my project?
    where should the codes be?

  3. John says:

    @Emmanuel
    Well, it really depends on what you are doing. I’m assuming that you have a swing project and have a main method of some sort. That’s probably the place to do it. You just have to add a JTextArea somewhere in your application then use the code in my second code block to initialize the TextAreaOutputStream.

  4. Lee says:

    Hi John, would that be okay to use the code in my project? It’s opensource and non-commercial.

    Thanks.

Leave a Reply

Your email address will not be published. Required fields are marked *