如何获得e.p printstacktrace()并将其存储为字符串变量? 我想稍后在程序中使用e.printStackTrace()生成的字符串。
我对Java还是个新手,所以我对StringWriter不太熟悉 将是解决方案。或者如果你有任何其他想法,请告诉我。谢谢
如何获得e.p printstacktrace()并将其存储为字符串变量? 我想稍后在程序中使用e.printStackTrace()生成的字符串。
我对Java还是个新手,所以我对StringWriter不太熟悉 将是解决方案。或者如果你有任何其他想法,请告诉我。谢谢
当前回答
StackTraceElement[] stack = new Exception().getStackTrace();
String theTrace = "";
for(StackTraceElement line : stack)
{
theTrace += line.toString();
}
其他回答
call: getStackTraceAsString(sqlEx)
public String getStackTraceAsString(Exception exc)
{
String stackTrace = "*** Error in getStackTraceAsString()";
ByteArrayOutputStream baos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream( baos );
exc.printStackTrace(ps);
try {
stackTrace = baos.toString( "UTF8" ); // charsetName e.g. ISO-8859-1
}
catch( UnsupportedEncodingException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
ps.close();
try {
baos.close();
}
catch( IOException ex )
{
Logger.getLogger(sss.class.getName()).log(Level.SEVERE, null, ex);
}
return stackTrace;
}
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();
}
沿着Guava的路线,Apache Commons Lang有ExceptionUtils。在org.apache.commons.lang.exception中获取fullstacktrace。来自StackOverflow上的先前答案。
你必须使用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) );
}
}