Java Utililty Methods Stacktrace to String

List of utility methods to do Stacktrace to String

Description

The list of methods to do Stacktrace to String are organized into topic(s).

Method

StringstackTrace()
Returns a stack trace of the current threads
return stackTrace("Stack Dump");
Stringstacktrace()
stacktrace
return stacktrace(new Exception("Stacktrace"));
Stringstacktrace2string(StackTraceElement[] stackTraceElements)
stacktracestring
StringBuffer stackTraceStringBuffer = new StringBuffer();
for (StackTraceElement stackTraceElement : stackTraceElements) {
    stackTraceStringBuffer.append(stackTraceElement.toString()).append("\n");
return stackTraceStringBuffer.toString();
StringstackTraceAsString(Exception ex)
stack Trace As String
ByteArrayOutputStream bos = new ByteArrayOutputStream();
PrintStream ps = new PrintStream(bos);
ex.printStackTrace(ps);
ps.flush();
ps.close();
return bos.toString();
booleanstackTraceContains(String... needles)
Determines whether the current stack trace contains the specified string.
final StringWriter writer = new StringWriter();
final PrintWriter out = new PrintWriter(writer);
new Exception().printStackTrace(out);
out.close();
final String haystack = writer.toString();
for (final String needle : needles) {
    if (haystack.contains(needle))
        return true;
...
StringstackTraceStr(Exception e)
stack Trace Str
String ret = "";
String msg = e.getMessage();
if (msg != null) {
    ret += msg + newline;
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
...
StringstackTraceString(Throwable t)
Return a stack trace as a string.
StringBuffer val = new StringBuffer();
boolean first = true;
while (t != null) {
    if (first) {
        val.append(t.toString() + "\n");
    } else {
        val.append("Cause: " + t + "\n");
    StackTraceElement[] stackTrace = t.getStackTrace();
    for (int j = 0; j < stackTrace.length; j++) {
        val.append("\tat " + stackTrace[j] + "\n");
    t = t.getCause();
return val.toString();
StringstackTraceToString(Exception e)
stack Trace To String
CharArrayWriter charArrayWriter = new CharArrayWriter();
PrintWriter printWriter = new PrintWriter(charArrayWriter);
e.printStackTrace(printWriter);
return new String(charArrayWriter.toCharArray());
StringstackTraceToString(Exception e, int nBack)
stack Trace To String
return stackTraceToString(e.getStackTrace(), nBack);
StringstackTraceToString(Exception ex, String message)
stack Trace To String
StringBuilder errMessage = new StringBuilder();
errMessage.append(message).append(": ").append(ex.getMessage()).append(":\n");
for (StackTraceElement line : ex.getStackTrace()) {
    errMessage.append(line.toString()).append("\n");
return errMessage.toString();