0

I am printing Stack Trace to JTextArea using the below code :

        try
        {
            throw new IOException();
        }
        catch(IOException e)
        {
            e.printStackTrace(pw);
            ta1.append(sw.toString());
        }
        pw.flush();
        sw.flush();
        try
        {
            throw new SQLException();
        }
        catch(SQLException e)
        {
            e.printStackTrace(pw);
            ta1.append(sw.toString());
        }

It prints out 2 IOException traces and 1 SQLExeption trace. Why is not stringwriter flushed out ?

I want 1 IOException trace and 1 SQLExeption trace.

Please suggest proper way to do this.

cruxion effux
  • 1,054
  • 3
  • 14
  • 27

1 Answers1

1

The flush method of StringWriter does nothing ! The flush method is just there to be compatible with java.io.Writer.

StringWriter source :

/**
 * Flush the stream.
 */
public void flush() {
}

And PrintWriter call the StringWriter flush method ...

PrintWriter source :

/**
 * Flushes the stream.
 * @see #checkError()
 */
public void flush() {
    try {
        synchronized (lock) {
            ensureOpen();
            out.flush();
        }
    }
    catch (IOException x) {
        trouble = true;
    }
}

So if you want to clear pw and sw you should not use flush method. You need to create a new one.

see :

What sense does it make to flush a StringWriter in Java?

How do you "empty" a StringWriter in Java?

Community
  • 1
  • 1
Dams
  • 997
  • 12
  • 28
  • what if program has a lot to print , so will I be creating new writers every time for just an append? Is there any other class than `StringWriter` which implements flush to clear its underlying buffer? – cruxion effux Jul 07 '15 at 15:51
  • It is difficult to help without the rest of code... Perhaps you can find a subclass of StringWriter with a flush method that works. Or rewrite your code without StringWriter ... StringBuilder / StringBuffer is specifically designed for assembling string (StringWriter use StringBuffer...) but i don't know if it is possible in your code. – Dams Jul 07 '15 at 16:44