java - 将堆栈跟踪打印到文本区域

标签 java exception

我使用以下代码将堆栈跟踪打印到 JTextArea :

        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());
        }

它打印出 2 个 IOException 跟踪和 1 个 SQLExeption 跟踪。 为什么 stringwriter 没有被刷新?

我想要 1 个 IOException 跟踪和 1 个 SQLExeption 跟踪。

请建议正确的方法来执行此操作。

最佳答案

StringWriterflush 方法什么都不做! flush 方法只是为了与 java.io.Writer 兼容。

StringWriter 来源:

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

并且PrintWriter调用StringWriter flush方法...

PrintWriter 来源:

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

所以如果你想清除pwsw你不应该使用flush方法。您需要创建一个新的。

参见:

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

How do you "empty" a StringWriter in Java?

关于java - 将堆栈跟踪打印到文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31265615/

相关文章:

java - 为什么 ArrayList.set() 留下一个方法没有任何异常?

exception - Java 8流-在迭代过程中引发异常

java - 单元测试旨在检查特定故障,但即使抛出了预期的异常,它仍然失败?

java - 使用选项类型是否不需要 if 语句?

java - 编码 RSA 算法 Java

c# - C# 中的 new Exception() 和 new Exception { } 有什么区别?

c# - 捕获大多数派生异常?

c# - 从BackgroundWorker到主线程的异常转发

java - Spring RestController提交文件

java - 是否有必要在 JPanel 上调用 setDoubleBuffered ?