【问题标题】:how to Print Exception in txt file in java [duplicate]如何在java中的txt文件中打印异常[重复]
【发布时间】:2013-08-02 08:37:21
【问题描述】:
public class myclass
{
    // Main method
    public static void main (String args[])
    {
        // Stream to write file
 try {
    int a=100;
     int b=a/0;
    System.out.println(b);
} catch (Exception e) {
    // TODO Auto-generated catch block
    e.printStackTrace();
}       


    }   
}

这是我的代码,我想打印 E:\logfile.txt 中出现的 Evre 异常。请帮助我,我无法做到这一点。

【问题讨论】:

  • 你需要替换e.printStackTrace...
  • 你有什么理由不想使用一些日志框架,例如Log4j?
  • 我将如何替换。 printStackTrace 请帮忙
  • 实际上我必须在服务器上上传,Ever Exception 需要在 E:\\log.txt 的 .txt 文件中收集什么
  • @AnilKumar 这就是日志库所做的事情,重写一个可能会浪费时间。

标签: java


【解决方案1】:

使用带有PrintStream 参数的printStackTrace() 重载:

http://docs.oracle.com/javase/7/docs/api/java/lang/Throwable.html#printStackTrace(java.io.PrintStream)

或者,使用日志框架,例如log4j

【讨论】:

    【解决方案2】:

    你可以为此编写一个类的静态方法。

    public class Logbook {
    
        // path to logbook
        private String path = "E:\logfile.txt";
    
        // static method
        public static boolean Log(String message) {
            try {
                File f = new File(path);
                // append the text file
                FileWriter fileWriter = new FileWriter(file,true);
    
                // append text to file by using a buffer
                BufferedWriter bw  = new BufferedWriter(fileWriter);
                fileWriter.append(message);
    
                // close buffer
                bufferFileWriter.close();
    
                // tell that it has succeed
                return true;
            }
            catch (Exception e) {
                return false;
            }
        }
    

    并记录消息,

    catch (Exception e) {
        // log file
        if (Logbook.Log(e.getMessage())) System.out.println("Error caught and got logged");
        else System.out.println("Error caught but logging has failed");
    }    
    

    【讨论】:

      猜你喜欢
      • 2018-11-11
      • 1970-01-01
      • 1970-01-01
      • 2020-11-14
      • 2016-01-15
      • 2017-04-05
      • 2014-02-13
      • 2022-11-24
      • 2021-03-19
      相关资源
      最近更新 更多