如何获取e.printStackTrace()
并将其存储到String
变量中?我想稍后在我的程序中使用由e.printStackTrace()
生成的字符串。
我对Java还很陌生,所以我不太熟悉StringWriter
,我认为它将是解决方案。或者如果你有任何其他想法,请让我知道。谢谢
发布于 2011-01-27 12:11:20
Guava通过Throwables.getStackTraceAsString(Throwable)让这一切变得简单
Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);
在内部,这做了@Zach L建议的事情。
发布于 2014-02-14 04:42:19
您可以使用Apache Commons 3类org.apache.commons.lang3.exception.ExceptionUtils
中的ExceptionUtils.getStackTrace(Throwable t);
。
http://commons.apache.org/proper/commons-lang/
ExceptionUtils.getStackTrace(Throwable t)
代码示例:
try {
// your code here
} catch(Exception e) {
String s = ExceptionUtils.getStackTrace(e);
}
发布于 2011-01-27 11:59:40
您必须使用getStackTrace ()
方法而不是printStackTrace()
。这是一个good example
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) );
}
}
https://stackoverflow.com/questions/4812570
复制相似问题