如何将printStackTrace()中的异常写入Java中的文本文件? [英] How do I write the exception from printStackTrace() into a text file in Java?
本文介绍了如何将printStackTrace()中的异常写入Java中的文本文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
try {
File f = new File();
}
catch(FileNotFoundException f){
f.printStackTrace(); //而不是打印到控制台它应该写入一个文本文件
writePrintStackTrace(f.getMessage()); //这是我自己的方法,我将f.getMessage()存储到文本文件中。
}
使用 getMessage()
作品,但它只显示错误信息。我想要 printStackTrace()
中的所有信息,包括行号。
解决方案
p>它接受 PrintStream
作为参数;请参阅文档。
文件文件=新建文件(test.log);
PrintStream ps = new PrintStream(file);
try {
// something
} catch(Exception ex){
ex.printStackTrace(ps);
}
ps.close();
另请参见 printStackTrace()和toString()之间的区别
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.
解决方案
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()
这篇关于如何将printStackTrace()中的异常写入Java中的文本文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文