31

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()行番号を含むすべての情報が必要です。

4

5 に答える 5

49

PrintStreamパラメータとして aを受け入れます。ドキュメントを参照してください。

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

printStackTrace() と toString() の違いも参照してください。

于 2012-08-21T10:37:32.997 に答える
10

この単純な例を拡張してみてください。

catch (Exception e) {

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

ご覧のとおり、printStackTrace()オーバーロードがあります。

于 2012-08-21T10:40:23.187 に答える
4

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);
于 2012-08-21T10:47:58.553 に答える
2

によってコンソールで印刷するために内部的に使用されるThrowableインターフェイスにAPI があります。getStackTrace()printStackTrace()

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

この API を試して、StackTraceElementこれらの要素を順番に取得して出力してください。

于 2012-08-21T10:39:42.747 に答える