如何获得e.p printstacktrace()并将其存储为字符串变量? 我想稍后在程序中使用e.printStackTrace()生成的字符串。

我对Java还是个新手,所以我对StringWriter不太熟悉 将是解决方案。或者如果你有任何其他想法,请告诉我。谢谢


当前回答

类似于

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

这正是你所需要的。

相关文档:

StringWriter PrintWriter Throwable

其他回答

类似于

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();

这正是你所需要的。

相关文档:

StringWriter PrintWriter Throwable

Guava通过Throwables.getStackTraceAsString(Throwable)使这变得容易:

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

在内部,这是@Zach L建议的。

StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
   theTrace += line.toString();
}

使用apache commons-lang3库

import org.apache.commons.lang3.exception.ExceptionUtils;

//...

String[] ss = ExceptionUtils.getRootCauseStackTrace(e);
logger.error(StringUtils.join(ss, System.lineSeparator()));

沿着Guava的路线,Apache Commons Lang有ExceptionUtils。在org.apache.commons.lang.exception中获取fullstacktrace。来自StackOverflow上的先前答案。