Mega Code Archive

 
Categories / Android / File
 

Save Exception to a file

import java.io.File; import java.io.FileNotFoundException; import java.io.FileOutputStream; import java.io.IOException; import java.text.SimpleDateFormat; import android.os.Environment; import android.util.Log; class Main {   private static final String TAG = "Tag";   private static final String DIRECTORY_SEPARATOR = System.getProperty("file.separator");   public static void ToFile(Exception exception) {     String timestamp = new SimpleDateFormat("yyyyMMddHHmmss").format(System         .currentTimeMillis());     File dirFile = new File(Environment.getExternalStorageDirectory()         + DIRECTORY_SEPARATOR + "WiMAXNotifier" + DIRECTORY_SEPARATOR         + "logs" + DIRECTORY_SEPARATOR);     dirFile.mkdirs();     File file = new File(dirFile, "wmnTrace_" + timestamp + ".stack");     FileOutputStream fileOutputStream = null;     try {       String stackString = Log.getStackTraceString(exception);       if (stackString.length() > 0) {         file.createNewFile();         fileOutputStream = new FileOutputStream(file);         fileOutputStream.write(stackString.getBytes());         fileOutputStream.flush();         fileOutputStream.close();       }     } catch (FileNotFoundException fileNotFoundException) {       Log.e("TAG", "File not found!", fileNotFoundException);     } catch (IOException ioException) {       Log.e("TAG", "Unable to write to file!", ioException);     }     return;   } }