Monday, August 18, 2014

How to Write Exceptions to a File in Android

  /**
   * @param e exception to be converted into String
   * @return
   */
  public static String writeException(Exception e) {
    final Writer result = new StringWriter();
    final PrintWriter printWriter = new PrintWriter(result);
    e.printStackTrace(printWriter);
    String stacktrace = result.toString();
    printWriter.close();
    return stacktrace;
  }

/**
   * @param context the context of the activity
   * @param folderName the folder name where the log is to be written
   * @param fileName the name of the file where the log needs to be written
   * @param text the text to be appended
   */

  public static void appendLog(Context context, String folderName, String fileName, String text) {

    String filePath = makeFolder(folderName);

    File logFile = new File(filePath + "/" + fileName);
    if (!logFile.exists()) {
      try {
        logFile.createNewFile();
      } catch (IOException e) {
        e.printStackTrace();
      }
    }
    try {
      // BufferedWriter for performance, true to set append to file flag
      BufferedWriter buf = new BufferedWriter(new FileWriter(logFile, true));
      buf.append("\n\n***********************\n" + text
          + "\n***********************");
      buf.newLine();
      buf.close();
    } catch (IOException e) {
      e.printStackTrace();
    }
  }

/**
* @param folderName
*            the name of the folder to be created
* @return returns the directory path <br>
*         <b>Note:</b> The directory will be created on the sdcard under
*         the App Name folder
*/
public String makeFolder(String folderName) {

File myDirectory = new File(Environment.getExternalStorageDirectory()
.toString() + "/" + getAppName(), folderName);

if (!myDirectory.exists()) {
myDirectory.mkdirs();
return myDirectory.toString();
}

return myDirectory.toString();
}

      /**
* @return returns the APP name
*/

public String getAppName(Context context) {

return context.getString(R.string.app_name);
}