如何将异常从 printStackTrace() 写入 Java 中的文本文件?

2022-09-01 09:27:40

我需要在Java的文本文件中捕获异常。例如:

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.
}

使用有效,但它只显示错误消息。我想要包含行号中的所有信息。getMessage()printStackTrace()


答案 1

它接受 a 作为参数;请参阅文档PrintStream

File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
    // something
} catch (Exception ex) {
    ex.printStackTrace(ps);
}
ps.close();

另请参阅 printStackTrace() 和 toString() 之间的区别


答案 2

尝试扩展这个简单的示例:

catch (Exception e) {

    PrintWriter pw = new PrintWriter(new File("file.txt"));
    e.printStackTrace(pw);
    pw.close();
}

如您所见,具有过载。printStackTrace()