package com.basic.security.utils; import android.os.Environment; import com.basic.security.activity.helper.MaFragments; import java.io.File; import java.io.FileOutputStream; import java.io.PrintWriter; import java.io.StringWriter; import java.io.Writer; import java.text.DateFormat; import java.text.SimpleDateFormat; import java.util.Date; import java.util.HashMap; import java.util.Map; public class LogFileUtils { private static DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd"); public static void logStacktraceToFile(MaFragments maFragments) { // if (1==1) { // return; // } try { throw new RuntimeException("showFragment"); } catch (Exception ex) { Map infos = new HashMap(); StringBuffer sb = new StringBuffer(); try { SimpleDateFormat sDateFormat = new SimpleDateFormat( "yyyy-MM-dd HH:mm:ss"); String date = sDateFormat.format(new java.util.Date()); sb.append("\r\n" + date + "\n"); for (Map.Entry entry : infos.entrySet()) { String key = entry.getKey(); String value = entry.getValue(); sb.append(key + "=" + value + "\n"); } Writer writer = new StringWriter(); PrintWriter printWriter = new PrintWriter(writer); ex.printStackTrace(printWriter); Throwable cause = ex.getCause(); while (cause != null) { cause.printStackTrace(printWriter); cause = cause.getCause(); } printWriter.flush(); printWriter.close(); String result = writer.toString(); sb.append(result); String fileName = writeFile(sb.toString()); } catch (Exception e) { sb.append("an error occured while writing file...\r\n"); } } } public static String getGlobalpath() { return Environment.getExternalStorageDirectory().getAbsolutePath() + File.separator + "debug" + File.separator; } private static String writeFile(String sb) throws Exception { String time = formatter.format(new Date()); String fileName = "crash-" + time + ".log"; // if (FileUtil.hasSdcard()) { if (true) { String path = getGlobalpath(); File dir = new File(path); if (!dir.exists()) dir.mkdirs(); System.out.println("LogFileUtils.writeFile " + path + fileName); FileOutputStream fos = new FileOutputStream(path + fileName, true); fos.write(sb.getBytes()); fos.flush(); fos.close(); } return fileName; } }