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();
}
-
Recent
- Saving the Java Exception Stack Trace into a file
- Problem with Tiles + Grails 1.1 (beta2)
- Integrating Tiles with Grails
- Displaying images from database records in Grails pages
- Saving images as blob in the database using Grails
- First Grails Project – BugTracker
- Newbie on Grails
- My New Year’s Resolution for 2009: Be Geekier.
-
Links
-
Archives
- March 2009 (1)
- January 2009 (7)
-
Categories
-
RSS
Entries RSS
Comments RSS