How to write Exception’s PrintStackTrace to a File in Java?

Usually, when you generate an exception in a Java program, you just print the exception to standard output using the below code statement

System.out.println("Got an Exception: " + e.getMessage());

But this is not what you want. Sometime you want to write Exception’s PrintStackTrace to a file and below Java program shows you how to write Exception’s PrintStackTrace to a file.

/****************************************************************************************
* Created on 03-2012 Copyright(c) https://kodehelp.com All Rights Reserved.
****************************************************************************************/
package com.kodehelp.javaio;

import java.io.File;
import java.io.FileNotFoundException;
import java.io.PrintStream;

/**
 * Created by https://kodehelp.com Date: 03/05/2012
 */
public class PrintStackTraceToFile {

    public static void main(String[] args) {
        PrintStream ps = null;
        try {
            ps = new PrintStream(new File("/sample.log"));
            throw new FileNotFoundException("Sample Exception");
        } catch (FileNotFoundException e) {
            e.printStackTrace(ps);
        }

    }

}