在Android开发过程中,可能需要自己记录一些log到SD卡。可以通过返回自定义的错误码来验证log是否保存成功。
代码见下:
public int SaveLog(String path, String fname, String log) {
isMount = Environment.getExternalStorageState();
if (isMount.equals("mounted")) {
File file = new File(path + fname);
File dir = new File(path);
;
try {
if (!file.exists()) {
dir.mkdirs();
FileOutputStream fos = new FileOutputStream(file);
OutputStreamWriter osw = new OutputStreamWriter(fos, FONT);
osw.write(log);
osw.flush();
osw.close();
return 0;
} else {
FileWriter fileWriter = new FileWriter(file, true);
fileWriter.write(log);
fileWriter.flush();
fileWriter.close();
return 1;
}
} catch (Exception e) {
e.printStackTrace();
return 2;
}
} else {
return -1;
}
}
自己没事儿封的方法,可以直接调用的哦~