How can I convert a stack trace to a string?

前端 未结 30 1198
再見小時候
再見小時候 2020-11-22 14:51

What is the easiest way to convert the result of Throwable.getStackTrace() to a string that depicts the stacktrace?

30条回答
  •  长发绾君心
    2020-11-22 15:21

    Printing stack trace to string

    import java.io.PrintWriter;
    import java.io.StringWriter;
    
    public class StackTraceUtils {
        public static String stackTraceToString(StackTraceElement[] stackTrace) {
            StringWriter sw = new StringWriter();
            printStackTrace(stackTrace, new PrintWriter(sw));
            return sw.toString();
        }
        public static void printStackTrace(StackTraceElement[] stackTrace, PrintWriter pw) {
            for(StackTraceElement stackTraceEl : stackTrace) {
                pw.println(stackTraceEl);
            }
        }
    }
    

    It's useful when you want to print the current thread stack trace without creating instance of Throwable - but note that creating new Throwable and getting stack trace from there is actually faster and cheaper than calling Thread.getStackTrace.

提交回复
热议问题