I need to capture the exception in a text file in Java. For example:
try {
File f = new File(\"\");
}
catch(FileNotFoundException f) {
f.printStackTrac
Try to expand on this simple example:
catch (Exception e) {
PrintWriter pw = new PrintWriter(new File("file.txt"));
e.printStackTrace(pw);
pw.close();
}
As you can see, printStackTrace()
has overloads.
Do set the err/out stream using System
class.
PrintStream newErr;
PrintStream newOut;
// assign FileOutputStream to these two objects. And then it will be written on your files.
System.setErr(newErr);
System.setOut(newOut);
It accepts a PrintStream
as a parameter; see the documentation.
File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
// something
} catch (Exception ex) {
ex.printStackTrace(ps);
}
ps.close();
See also Difference between printStackTrace() and toString()
Hope below example helps you-
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);
}
}
}
For more detail, refer to this link here
There is an API in Throwable
interface getStackTrace()
which is used internally for printing in console by printStackTrace()
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace()
Try this API to get StackTraceElement
and print those elements sequentially.