Java Throwable to String stackTrace(Throwable exception)

Here you can find the source of stackTrace(Throwable exception)

Description

Returns the stack trace of an Throwable as a String.

License

Apache License

Parameter

Parameter Description
e - an instance of <code>Throwable</code>

Return

the exception's stack trace as a String

Declaration

public static String stackTrace(Throwable exception) 

Method Source Code

//package com.java2s;
//License from project: Apache License 

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;

import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import java.io.PrintStream;

public class Main {
    /**// w  w w  .j a v  a  2  s  .  co m
     * Returns the stack trace of an <code>Throwable</code>
     * as a <code>String</code>.
     *
     * @param e - an instance of <code>Throwable</code>
     *
     * @return the exception's stack trace as a
     *    <code>String</code>
     */
    public static String stackTrace(Throwable exception) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        PrintStream printStream = new PrintStream(outputStream);
        exception.printStackTrace(printStream);
        return outputStream.toString();

    }

    public static String toString(File file) throws IOException {
        FileInputStream inputStream = new FileInputStream(file);
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
        copy(inputStream, outputStream);
        return outputStream.toString();

    }

    /**
     * Reads the bytes from the input and writes them to the
     * output.
     *
     * @param input - the input stream
     * @param output - the output stream
     *
     */
    public static void copy(InputStream in, OutputStream out) throws IOException {
        byte[] b = new byte[10240]; // 10K buffer
        int result = in.read(b);
        while (result != -1) {
            out.write(b, 0, result);
            result = in.read(b);
        }
    }
}

Related

  1. stackTrace(Throwable cause)
  2. stackTrace(Throwable e)
  3. stackTrace(Throwable e)
  4. stackTrace(Throwable e)
  5. stackTrace(Throwable e)
  6. stackTrace(Throwable t)
  7. stackTrace(Throwable t)
  8. stackTrace(Throwable t)
  9. stackTrace(Throwable th)