java保存log到文件中

public class LogUtil {


public static  boolean isDebug = true;


public static void log(Object paramObject) {
try{
LogUtil.log(Utils.TAG, paramObject.toString());
}catch (Exception e){
}
}


public static void log(String paramString, Object paramObject) {
if (isDebug) {
Log.d(paramString, paramObject.toString());
saveToSDCard(paramString  +"  :" + getDate()+"  :"  + paramObject.toString());
}
}


public static void logErr(Throwable paramObject) {
if (isDebug) {
final Writer result = new StringWriter();
final PrintWriter printWriter = new PrintWriter(result);
paramObject.printStackTrace(printWriter);
LogUtil.log("Exception:" + result.toString());
printWriter.close();
}
}
private static String getDate() {
SimpleDateFormat format=new SimpleDateFormat("MM-dd HH:mm:ss.SSS");
String time=format.format(new Date());
return time;
}


/**
* 追加文件:使用FileWriter
*
* @param content
*/
private static void saveToSDCard(String content) {
try {
// 打开一个写文件器,构造函数中的第二个参数true表示以追加形式写文件
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
String path = Environment.getExternalStorageDirectory() + "/baby/baby.log";
File file = new File(path);
if (!file.exists() || file.isDirectory()) {
file.getParentFile().mkdirs();
file.createNewFile();
}
FileWriter writer = new FileWriter(path, true);
writer.write(content + "\n");
writer.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void clearLog(){
if (!Environment.getExternalStorageState().equals(Environment.MEDIA_MOUNTED)) {
return;
}
String path = Environment.getExternalStorageDirectory() + "/ihome/ihome.log";
File file = new File(path);
if (file.exists()) {
file.delete();
}
}
}

你可能感兴趣的:(java保存log到文件中)