我使用以下代码将堆栈跟踪打印到 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
跟踪。
请建议正确的方法来执行此操作。
最佳答案
StringWriter
的 flush
方法什么都不做!
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;
}
}
所以如果你想清除pw
和sw
你不应该使用flush
方法。您需要创建一个新的。
参见:
关于java - 将堆栈跟踪打印到文本区域,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/31265615/