简体   繁体   中英

How to convert a StackTraceElement[] to a String?

Thread.getStackTrace() returns StackTraceElement[] . How can I convert this to a String with the same format as Exception.printStackTrace() returns?

To clarify: I don't have an exception, only a thread. I want to display the thread's stack trace using the same format as exception stack traces.

It is super easy, you just have to print them, with whatever prefix you want.

To print same as printStackTrace() , the prefix would be "\\tat " .

Proof

// Show printStackTrace() output
new RuntimeException().printStackTrace(System.out);

// Similar output using getStackTrace()
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
System.out.println("getStackTrace()");
for (int i = 1; i < stackTrace.length; i++)
    System.out.println("\tat " + stackTrace[i]);

Output

java.lang.RuntimeException
    at Test.main(Test.java:5)
getStackTrace()
    at Test.main(Test.java:8)

Note how for loop skipped index 0, since that is the stack frame for getStackTrace() itself.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM