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

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

Leave a Comment