Formats a specified exception stack trace as a single string. - Java java.lang

Java examples for java.lang:Exception StackTrace

Description

Formats a specified exception stack trace as a single string.

Demo Code

/**//from   www.java2 s. c  o m
 * This file is part of Apache Spark Benchmark.
 *
 * Apache Spark Benchmark is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License as published by
 * the Free Software Foundation; either version 2, or (at your option) any later
 * version.
 *
 * Apache Spark Benchmark is distributed in the hope that it will be useful, but
 * WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or
 * FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
 * details.
 *
 * You should have received a copy of the GNU General Public License along with
 * this program; see the file COPYING. If not, see
 * <http://www.gnu.org/licenses/>.
 */
import java.io.*;
import java.text.*;
import java.util.*;

public class Main{
    /**
     * New Line String
     */
    public static String NEW_LINE = System.getProperty("line.separator");
    /**
     * Formats a specified exception stack trace as a single string. (for
     * written to the results.txt file at the end of a result line)
     *
     * @param e an exception to format its stack trace
     * @return the stack trace as a single sting.
     */
    public static String formatStackTrace(Throwable e) {
        // Convert the stack to a string:
        ByteArrayOutputStream out = new ByteArrayOutputStream(1024);
        try (PrintWriter writer = new PrintWriter(out)) {
            e.printStackTrace(writer);
        }
        String stackTrace = out.toString();
        // Replace new lines with a delimiter:
        String delimiter = "|||";
        stackTrace = stackTrace.replace(NEW_LINE, delimiter);
        stackTrace = stackTrace.replace("\r\n", delimiter);
        stackTrace = stackTrace.replace("\r", delimiter);
        stackTrace = stackTrace.replace("\n", delimiter);
        // Return the result single line string:
        return stackTrace;
    }
}

Related Tutorials