简体   繁体   English

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

[英]How do I write the exception from printStackTrace() into a text file in Java?

I need to capture the exception in a text file in Java. 我需要在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. 使用getMessage()有效,但它只显示错误消息。 I want all the information in the printStackTrace() including line numbers. 我想要printStackTrace()中的所有信息,包括行号。

It accepts a PrintStream as a parameter; 它接受PrintStream作为参数; 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()和toString()之间的区别

Try to expand on this simple example: 尝试扩展这个简单的例子:

catch (Exception e) {

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

As you can see, printStackTrace() has overloads. 如您所见, printStackTrace()具有重载功能。

Do set the err/out stream using System class. 使用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);

There is an API in Throwable interface getStackTrace() which is used internally for printing in console by printStackTrace() Throwable接口中有一个API getStackTrace() ,它通过printStackTrace()在内部用于在控制台中打印

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

Try this API to get StackTraceElement and print those elements sequentially. 尝试使用此API获取StackTraceElement并按顺序打印这些元素。

Hope below example helps you- 希望以下示例可以帮助您 -

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

For more detail, refer to this link here 更多详细信息,请参阅此链接在这里

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM