很多人在自己的项目中加入了日志管理系统,有的是自己写的,有的则是用的别人写好的依赖库,但是不是所有的依赖库都能满足我们的需求,这时候是不是要自己往上添加呢
背景,接手的项目里面已经加好日志管理了,但是没有定期清理的功能,我看连两年前的文件都在,一天一个txt文件,虽然不大,但是量多啊,所以还是有必要加定期清理的
上代码:
/**
* Created by Forrest.
* User: Administrator
* Date: 2020/12/11
* Description:
*/
public class DelFile {
public static void del(Context context) {
String path = "/sdcard/dhypda/logs/";
File file = new File(path);
File[] files = file.listFiles();// 读取
getFileName(files, context);
}
private static void getFileName(File[] files, Context context) {
if (files != null) {// 先判断目录是否为空,否则会报空指针
for (File file : files) {
if (file.isDirectory()) {
getFileName(file.listFiles(), context);
} else {
String fileName = file.getName();
if (fileName.endsWith(".txt")) {
try {
String s = fileName.substring(0, fileName.lastIndexOf(".")).toString();
String ph = "/sdcard/dhypda/logs/" + "" + s.trim() + ".txt";
File fe = new File(ph);
Log.i("test", ph + "/" + s.trim() + "/" + getStringToday() + "/" + daysBetween(s.trim(), getStringToday()));
if (daysBetween(s.trim(), getStringToday()) >= 7) {
fe.delete();
}
} catch (ParseException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}// 当前时间
}
}
}
}
}
/**
* 得到现在时间
*
* @return 字符串 yyyyMMdd HHmmss
*/
public static String getStringToday() {
Date currentTime = new Date();
SimpleDateFormat formatter = new SimpleDateFormat("yyyyMMdd");
String dateString = formatter.format(currentTime);
return dateString;
}
/**
* 字符串的日期格式的计算
*/
public static int daysBetween(String smdate, String bdate) throws ParseException {
SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
Calendar cal = Calendar.getInstance();
cal.setTime(sdf.parse(smdate));
long time1 = cal.getTimeInMillis();
cal.setTime(sdf.parse(bdate));
long time2 = cal.getTimeInMillis();
long between_days = (time2 - time1) / (1000 * 3600 * 24);
return Integer.parseInt(String.valueOf(between_days));
}
}
直接用就行
原理很简单
1.找到我们存储日志的目录
2.找到后缀为txt的文件
3因为我的日志是以yyyyMMdd格式命名的,所以直接算出当前时间和文件名字时间的时间差就ok了
4根据时间差删除超出时间的文件
就酱~