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

后端 未结 5 1097
故里飘歌
故里飘歌 2020-12-03 03:00

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

try {
  File f = new File(\"\");
}
catch(FileNotFoundException f) {
  f.printStackTrac         


        
5条回答
  •  离开以前
    2020-12-03 03:36

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

提交回复
热议问题