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

后端 未结 5 1088
故里飘歌
故里飘歌 2020-12-03 03:00

I need to capture the exception in a text file in Java. For example:

try {
  File f = new File(\"\");
}
catch(FileNotFoundException f) {
  f.printStackTrac         


        
相关标签:
5条回答
  • 2020-12-03 03:18

    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.

    0 讨论(0)
  • 2020-12-03 03:30

    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);
    
    0 讨论(0)
  • 2020-12-03 03:36

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

    0 讨论(0)
  • 2020-12-03 03:36

    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

    0 讨论(0)
  • 2020-12-03 03:39

    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.

    0 讨论(0)
提交回复
热议问题