如何将printStackTrace()中的exception写入Java中的文本文件?
我需要在Java中的文本文件中捕获exception。 例如:
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()
中的所有信息,包括行号。
它接受PrintStream
作为参数; 看文档 。
File file = new File("test.log"); PrintStream ps = new PrintStream(file); try { // something } catch (Exception ex) { ex.printStackTrace(ps); } ps.close();
另请参见printStackTrace()和toString()之间的区别
尝试扩展这个简单的例子:
catch (Exception e) { PrintWriter pw = new PrintWriter(new File("file.txt")); e.printStackTrace(pw); pw.close(); }
如您所见, printStackTrace()
具有重载。
使用System
类设置err / out流。
PrintStream newErr; PrintStream newOut; // assign FileOutputStream to these two objects. And then it will be written on your files. System.setErr(newErr); System.setOut(newOut);
Throwable
接口中有一个API getStackTrace()
,它通过printStackTrace()
在内部用于在控制台中打印
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace ()
尝试使用此API获取StackTraceElement
并按顺序打印这些元素。
希望以下例子可以帮助你 –
package com.kodehelp.javaio; import java.io.File; import java.io.FileNotFoundException; import java.io.PrintStream; /** * Created by https://kodehelp.com * Date: 03/05/2012 */ public class PrintStackTraceToFile { public static void main(String[] args) { PrintStream ps= null; try { ps = new PrintStream(new File("/sample.log")); throw new FileNotFoundException("Sample Exception"); } catch (FileNotFoundException e) { e.printStackTrace(ps); } } }
有关更多详细信息,请参阅此链接