无法抓取log时将log写入到文件中的方法
public static void log(String tag, String str) {
File file = null;
try {
file = new File("storage/sdcard0/log.txt");
if(!file.exists()) {
file.createNewFile();
}
} catch (IOException e1) {
e1.printStackTrace();
}
if (file == null) {
return;
}
FileWriter fw = null;
try {
fw = new FileWriter(file, true);
fw.append("\n" + System.currentTimeMillis() + "\t" + tag + ",\t" + str);
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fw != null) {
try {
fw.flush();
fw.close();
} catch (IOException e) {
e.printStackTrace();
}
fw = null;
}
}
}
模板
1.实现
public String LOG_FILE_NAME = "/mnt/sdcard/test_01.log";
private String getTimeString() {
java.util.Date now= new Date();
java.text.SimpleDateFormat formatter = new java.text.SimpleDateFormat("yy-MM-dd HH:mm:ss.sss");
String rlt = formatter.format(now);
return rlt;
}
private void saveLog( String log) {
try {
OutputStream os=new FileOutputStream(LOG_FILE_NAME, true);
os.write(log.getBytes());
os.flush();
os.close();
}catch(Exception ex){
ex.printStackTrace();
}
}
private void writeLog(String out) {
String log = getTimeString()+": "+out+"\n";
saveLog(log);
}
2.测试
String str = "123456";
String log = str;
writeLog(log);