【问题标题】:How do I write the exception from printStackTrace() into a text file in Java?如何将 printStackTrace() 中的异常写入 Java 中的文本文件?
【发布时间】:2012-08-16 16:38:10
【问题描述】:

我需要在 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() 中的所有信息,包括行号。

【问题讨论】:

  • 为什么不使用日志框架?这就是他们所擅长的。

标签: java exception


【解决方案1】:

它接受PrintStream 作为参数;见documentation。

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

另见Difference between printStackTrace() and toString()

【讨论】:

  • @Qnan Google 并不总是最新的。 ;)
【解决方案2】:

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

catch (Exception e) {

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

如您所见,printStackTrace() 有重载。

【讨论】:

    【解决方案3】:

    请使用System 类设置错误/输出流。

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

    【讨论】:

    • 或者选择像log4j这样的日志框架
    【解决方案4】:

    Throwable 接口getStackTrace() 中有一个API,在printStackTrace() 内部用于在控制台中打印

    http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace()

    尝试使用此 API 获取 StackTraceElement 并按顺序打印这些元素。

    【讨论】:

      【解决方案5】:

      希望下面的例子对你有所帮助-

      package com.kodehelp.javaio;
      
      import java.io.File;
      import java.io.FileNotFoundException;
      import java.io.PrintStream;
      
      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);
            }
          }
      }
      

      更多详情请参考此链接here

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2012-03-10
        • 2014-12-13
        • 2015-05-18
        • 1970-01-01
        • 2018-10-19
        • 2012-01-27
        相关资源
        最近更新 更多