Skip to content
Advertisement

How do I write the exception from printStackTrace() into a text file in Java?

I need to capture the exception in a text file in Java. For example:

try {
  File f = new File("");
}
catch(FileNotFoundException f) {
  f.printStackTrace();  // instead of printing into console it should write into a text file    
  writePrintStackTrace(f.getMessage()); // this is my own method where I store f.getMessage() into a text file.
}

Using getMessage() works, but it only shows the error message. I want all the information in the printStackTrace() including line numbers.

Advertisement

Answer

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()

Advertisement