簡體   English   中英

如何將printStackTrace()中的異常寫入Java中的文本文件?

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

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

它接受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);
      }
    }
}

更多詳細信息,請參閱此鏈接在這里

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM