我需要在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.
}
Run Code Online (Sandbox Code Playgroud)
使用getMessage()作品,但它只显示错误消息.我想要printStackTrace()包含行号的所有信息.
Qna*_*nan 40
它接受PrintStream一个参数; 看文档.
File file = new File("test.log");
PrintStream ps = new PrintStream(file);
try {
// something
} catch (Exception ex) {
ex.printStackTrace(ps);
}
ps.close();
Run Code Online (Sandbox Code Playgroud)
另请参见printStackTrace()和toString()之间的区别
尝试扩展这个简单的例子:
catch (Exception e) {
PrintWriter pw = new PrintWriter(new File("file.txt"));
e.printStackTrace(pw);
pw.close();
}
Run Code Online (Sandbox Code Playgroud)
如你所见,printStackTrace()有重载.
| 归档时间: |
|
| 查看次数: |
37344 次 |
| 最近记录: |