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

DeeKay March 5, 2012 at 7:00 pm · java.io

Below Java program shows you how to write Exception’s PrintStackTrace to a file.

 

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

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

/**
 * Created by http://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) {
			// TODO Auto-generated catch block
			e.printStackTrace(ps);
		}

	}

}