How can I convert a stack trace to a string?

前端 未结 30 1169
再見小時候
再見小時候 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:20

    This should work:

    StringWriter sw = new StringWriter();
    e.printStackTrace(new PrintWriter(sw));
    String exceptionAsString = sw.toString();
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-11-22 15:22

    With Java 8 Stream API you can do something like this:

    Stream
        .of(throwable.getStackTrace())
        .map(StackTraceElement::toString)
        .collect(Collectors.joining("\n"));
    

    It will take array of stack trace elements, convert them to string and join into multiline string.

    0 讨论(0)
  • 2020-11-22 15:24
    public static String getStackTrace(Throwable t) {
        StringWriter sw = new StringWriter();
        t.printStackTrace(new PrintWriter(sw));
        return sw.toString();
    }
    
    0 讨论(0)
  • 2020-11-22 15:24

    Print the stack trace to a PrintStream, then convert it to a String:

    // ...
    
    catch (Exception e)
    {
        ByteArrayOutputStream out = new ByteArrayOutputStream(); 
        e.printStackTrace(new PrintStream(out));
        String str = new String(out.toByteArray());
    
        System.out.println(str);
    }
    
    0 讨论(0)
  • 2020-11-22 15:24

    Code from Apache Commons Lang 3.4 (JavaDoc):

    public static String getStackTrace(final Throwable throwable) {
        final StringWriter sw = new StringWriter();
        final PrintWriter pw = new PrintWriter(sw, true);
        throwable.printStackTrace(pw);
        return sw.getBuffer().toString();
    }
    

    The difference with the other answers is that it uses autoFlush on the PrintWriter.

    0 讨论(0)
提交回复
热议问题