1.问题:
有时候一些问题在自己电脑工作环境没法复现,需要收集查看错误日志,故把错误日志保存在用户手机本地;
2.代码:
public static boolean string2File(String res, String filePath) {
boolean flag = true;
BufferedReader bufferedReader = null;
BufferedWriter bufferedWriter = null;
try {
File distFile = new File(filePath);
if (!distFile.getParentFile().exists()) distFile.getParentFile().mkdirs();
bufferedReader = new BufferedReader(new StringReader(res));
bufferedWriter = new BufferedWriter(new FileWriter(distFile,true));
char buf[] = new char[1024]; //字符缓冲区
int len;
while ((len = bufferedReader.read(buf)) != -1) {
bufferedWriter.write(buf, 0, len);
}
bufferedWriter.flush();
bufferedReader.close();
bufferedWriter.close();
} catch (IOException e) {
e.printStackTrace();
flag = false;
return flag;
} finally {
if (bufferedReader != null) {
try {
bufferedReader.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return flag;
}
3.使用:
errorResult=e.toString()+"-----"+new Date().toString()+"\n";
string2File(errorResult,"/storage/emulated/0/myapp/errorlog.txt");
4.说明
上述代码中,这个是日志书写追加的,若需要书写覆盖,只需改动上面一行代码:
bufferedWriter = new BufferedWriter(new FileWriter(distFile,true));