Monday, July 20, 2009

Saving the Java Exception Stack Trace into a file

If we want to get the Stack Trace of a Java Exception, we can't simply use exception.printStackTrace() because that method returns nothing and just prints the stack trace into the console.

To get the Stack Trace and store it into a file, you can do this:


StringBuilder sb = new StringBuilder();
StackTraceElement[] stackTrace = exception.getStackTrace();
for(int i=0;i<stackTrace.length;i++){
sb.append(stackTrace[i]);
sb.append("\n");
}


Given the StringBuilder sb above, you can proceed to write the string in a file. This is how i would do it:

FileOutputStream fos = new FileOutputStream(filename);
try{
OutputStreamWriter osw = new OutputStreamWriter(fos);
try{
BufferedWriter bw = new BufferedWriter(osw);
try{
bw.write(sb.toString());
}finally{
bw.close();
}
}finally{
osw.close();
}
}finally{
fos.close();
}


Similarly, you can merge the 2 codes above like below:

FileOutputStream fos = new FileOutputStream(filename);
try{
OutputStreamWriter osw = new OutputStreamWriter(fos);
try{
BufferedWriter bw = new BufferedWriter(osw);
try{
StackTraceElement[] stackTrace = exception.getStackTrace();
for(int i=0;i<stackTrace.length;i++){
bw.write(stackTrace[i]);
bw.newLine();
}
}finally{
bw.close();
}
}finally{
osw.close();
}
}finally{
fos.close();
}

No comments:

Post a Comment