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 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) All Rights Reserved.
package com.kodehelp.javaio;


 * Created by
 * 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



Please Post Your Comments & Reviews

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.