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

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

Usually when you generate an exception in a Java program, you just print the exception to standard output using 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.

 

<br />
/****************************************************************************************<br />
 * Created on 03-2012 Copyright(c) http://kodehelp.com All Rights Reserved.<br />
 ****************************************************************************************/<br />
package com.kodehelp.javaio;</p>
<p>import java.io.File;<br />
import java.io.FileNotFoundException;<br />
import java.io.PrintStream;</p>
<p>/**<br />
 * Created by http://kodehelp.com<br />
 * Date: 03/05/2012<br />
 */<br />
public class PrintStackTraceToFile {</p>
<p>	public static void main(String[] args) {<br />
		PrintStream ps= null;<br />
		try {<br />
			ps = new PrintStream(new File("/sample.log"));<br />
			throw new FileNotFoundException("Sample Exception");<br />
		} catch (FileNotFoundException e) {<br />
			// TODO Auto-generated catch block<br />
			e.printStackTrace(ps);<br />
		}</p>
<p>	}</p>
<p>}<br />