35

I need to capture the exception in a text file in 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. I want all the information in the printStackTrace() including line numbers.

james.garriss
  • 12,959
  • 7
  • 83
  • 96
Sri
  • 669
  • 2
  • 13
  • 25

5 Answers5

54

It accepts a PrintStream as a parameter; 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()

Community
  • 1
  • 1
Qnan
  • 3,714
  • 18
  • 15
10

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.

Less
  • 3,047
  • 3
  • 35
  • 46
4

Do set the err/out stream using System class.

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);
pratikabu
  • 1,672
  • 14
  • 17
2

There is an API in Throwable interface getStackTrace() which is used internally for printing in console by printStackTrace()

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.

sundar
  • 1,760
  • 12
  • 28
0

Hope below example helps you-

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

For more detail, refer to this link here

Dinesh K
  • 351
  • 1
  • 5
  • 9