实际开发中,需要把一些关键日志记录在手机中
这个时候一般会新建一个.txt文件用来保存这些日志
于是写了这样一个工具类
方便保存和查看相关的日志记录
具体代码如下:
/**
* Created by lenovo on 2019/10/28.
* 日志记录工具
*/
public class FileUtil {
//是否保存日志
public static final boolean isLog = true;
//存储路径
public static final String mStrU = Environment.getExternalStorageDirectory().getAbsolutePath() + "/zzctest.txt";
/**
* @param context
* @param msg 记录信息
*/
public static void writeMsgIntoFile(final Context context, final String msg) {
if (context == null || isNullOrNil(msg) || isNullOrNil(mStrU) || !isLog) {
return;
}
File file = new File(mStrU);
if (!file.exists() && !file.getParentFile().exists()) {
file.getParentFile().mkdirs();
}
try {
FileWriter fw = new FileWriter(mStrU, true);
fw.write(msg + "\n");//加上换行
fw.flush();
fw.close();
notifySystemToScan(context, file);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* 得到格式化时间
*
* @param date
* @param format
* @return
*/
public static String getFormatTime(Date date, String format) {
if (date == null || isNullOrNil(format)) {
return null;
}
SimpleDateFormat dateFormater = new SimpleDateFormat(format);
return dateFormater.format(date);
}
/**
* 扫描sd卡,进行更新
*
* @param context
* @param file
*/
public static void notifySystemToScan(Context context, File file) {
if (context == null || file == null || !file.exists()) {
return;
}
Intent intent = new Intent(Intent.ACTION_MEDIA_SCANNER_SCAN_FILE);
Uri uri = Uri.fromFile(file);
intent.setData(uri);
context.sendBroadcast(intent);
}
/**
* 判断字符串是否为空
* @param str
* @return
*/
public static boolean isNullOrNil(String str) {
if (str == null || str.length() == 0) {
return true;
}
return false;
}
}
使用时直接调用writeMsgIntoFile()这个静态方法就好
记得加上相关的读取和写入权限:
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE"/>
<uses-permission android:name="android.permission.WRITE_EXTERNAL_STORAGE"/>