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

后端 未结 5 1101
故里飘歌
故里飘歌 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: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

提交回复
热议问题