Eu preciso capturar a exceção em um arquivo de texto em Java. Por exemplo:
try { File f = new File(""); } catch(FileNotFoundException f) { f.printStackTrace(); // instead of printing into console it should write into a text file writePrintStackTrace(f.getMessage()); // this is my own method where I store f.getMessage() into a text file. }
Usando getMessage()
funciona, mas mostra apenas a mensagem de erro. Eu quero todas as informações no printStackTrace()
incluindo números de linha.
Aceita um PrintStream
como parâmetro; veja a documentação .
File file = new File("test.log"); PrintStream ps = new PrintStream(file); try { // something } catch (Exception ex) { ex.printStackTrace(ps); } ps.close();
Veja também Diferença entre printStackTrace () e toString ()
Tente expandir este exemplo simples:
catch (Exception e) { PrintWriter pw = new PrintWriter(new File("file.txt")); e.printStackTrace(pw); pw.close(); }
Como você pode ver, printStackTrace()
tem sobrecargas.
Defina o stream err / out usando a class System
.
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);
Há uma API na interface Throwable
, getStackTrace()
que é usada internamente para impressão no console por printStackTrace()
http://docs.oracle.com/javase/1.4.2/docs/api/java/lang/Throwable.html#getStackTrace ()
Experimente esta API para obter o StackTraceElement
e imprimi-los sequencialmente.
Espero abaixo exemplo ajuda você-
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); } } }
Para mais detalhes, consulte este link aqui