如何将printStackTrace存储到字符串中

ace*_*ace 208 java stack-trace

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

我还是Java的新手,所以我不太熟悉StringWriter,我认为这将是解决方案.或者,如果您有任何其他想法,请告诉我.谢谢

Zac*_*h L 432

有点像

StringWriter errors = new StringWriter();
ex.printStackTrace(new PrintWriter(errors));
return errors.toString();
Run Code Online (Sandbox Code Playgroud)

应该是你需要的.

相关文件:

  • 在使用后关闭`PrintWriter`以释放资源怎么样?阅读我发现的文档对于StringWriter来说并不是必需的. (4认同)
  • 这也打印了抛出异常的嵌套原因,这正是我所需要的.谢谢! (2认同)

Col*_*inD 71

使用Throwables.getStackTraceAsString(Throwable),Guava使这一切变得简单:

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);
Run Code Online (Sandbox Code Playgroud)

在内部,这就是@Zach L所建议的.


Mih*_*ila 14

沿着Guava,Apache Commons Lang已经ExceptionUtils.getFullStackTrace进入了org.apache.commons.lang.exception.来自 StackOverflow 的先前答案.


thi*_*goh 14

您可以使用ExceptionUtils.getStackTrace(Throwable t);Apache Commons 3类org.apache.commons.lang3.exception.ExceptionUtils.

http://commons.apache.org/proper/commons-lang/

ExceptionUtils.getStackTrace(Throwable t)

代码示例:

try {

  // your code here

} catch(Exception e) {
  String s = ExceptionUtils.getStackTrace(e);
}
Run Code Online (Sandbox Code Playgroud)


小智 13

你必须使用getStackTrace ()方法而不是printStackTrace().这是一个很好的例子:

import java.io.*;

/**
* Simple utilities to return the stack trace of an
* exception as a String.
*/
public final class StackTraceUtil {

  public static String getStackTrace(Throwable aThrowable) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    aThrowable.printStackTrace(printWriter);
    return result.toString();
  }

  /**
  * Defines a custom format for the stack trace as String.
  */
  public static String getCustomStackTrace(Throwable aThrowable) {
    //add the class name and any message passed to constructor
    final StringBuilder result = new StringBuilder( "BOO-BOO: " );
    result.append(aThrowable.toString());
    final String NEW_LINE = System.getProperty("line.separator");
    result.append(NEW_LINE);

    //add each element of the stack trace
    for (StackTraceElement element : aThrowable.getStackTrace() ){
      result.append( element );
      result.append( NEW_LINE );
    }
    return result.toString();
  }

  /** Demonstrate output.  */
  public static void main (String... aArguments){
    final Throwable throwable = new IllegalArgumentException("Blah");
    System.out.println( getStackTrace(throwable) );
    System.out.println( getCustomStackTrace(throwable) );
  }
} 
Run Code Online (Sandbox Code Playgroud)

  • [Zach 的解决方案](/sf/answers/336881261/) 是 3 行代码。 (2认同)

Jon*_*ust 6

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