Pregunta

In java, when we catch a exception, we usually can use printStackTrace() method to print the error information, and we can also use printStackTrace(PrintStream out) to direct those information to a file.

But how can I append those information into a existing file, just like using out.append()?

¿Fue útil?

Solución

You must open file in append mode:

try {
    //...
} catch (Exception e) {
    try(Writer w = new FileWriter("file.log", true)) {
        e.printStackTrace(new PrintWriter(new BufferedWriter(w)));
    }
}

If you are not using Java 7, you must remember about closing or at least flushing the Writer. Or you can have a global Writer, but then you must synchronize it between threads.

What about simply using some existing Java library like , or even java.util.logging? Simply say:

} catch (Exception e) {
    log.error("Opps!", e);
}

...and the framework will log the exception wherever you want, with lots of additional data like thread name, timestamp, additional message, etc. Logback can also show you from which library given stack frame comes from and even print the stack trace starting from root cause (most nested exception).

Otros consejos

We can redirect the error stream to a file

System.setErr(new PrintStream(new FileOutputStream("errors.txt", true), true));

then Throwable.printStackTrace() will print to errors.txt.

"true" in FileOutputStream constructor means "append"; "true" in PrintStream condtructor means "autoflush". We do not need to worry about never closing FileOutputStream, OS will close it when the app ends.

Licenciado bajo: CC-BY-SA con atribución
No afiliado a StackOverflow
scroll top