如何在java中的txt文件中打印异常

时间:2013-08-02 08:37:21

标签: java

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 Exception。请帮助我,我无法做到这一点。

2 个答案:

答案 0 :(得分:4)

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

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

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

答案 1 :(得分:0)

您可以为此编写类的静态方法。

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