数据清空

未上传
杭州-烟草
LAPTOP-S9HJSOEB\昊天 4 months ago
parent c660047d5a
commit e4da015e86

@ -14,6 +14,7 @@ import org.springframework.scheduling.annotation.EnableScheduling;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;
import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.File;
import java.io.IOException;
@ -51,7 +52,16 @@ public class CronTab {
@Resource
private LightSourceService lightSourceService;
@Scheduled(cron = "0 0 0 * * ?")
/**
* 软件启动时自动触发一次文件清理
*/
@PostConstruct
public void initFileClean() {
log.info(" startup file cleanup");
file();
}
// @Scheduled(cron = "0 0 0 * * ?")
//@Scheduled(cron = "0 0/1 * * * *")
public void file() {
log.info(" corn delete file");
@ -99,34 +109,44 @@ public class CronTab {
// }
/**
* 递归检查并删除目录下所有超期的文件,最后清理空目录
* @param dir 目标目录(会遍历其下所有子目录、子文件)
* @param days 文件保留天数,超过此天数的文件将被删除
*/
public static void checkFileTime(File dir, int days) {
if (!dir.exists()) {
return;
}
if (dir.isDirectory()) {
String[] children = dir.list();
if(children.length == 0){
log.info("delete path:{}",dir.getPath());
dir.delete();
if (children != null) {
// 递归处理所有子文件和子目录
for (String child : children) {
checkFileTime(new File(dir, child), days);
}
for (int i = 0; i < children.length; i++) {
checkFileTime(new File(dir, children[i]),days);
}
// 处理完所有子项后,检查当前目录是否已空,若为空则删除
String[] remaining = dir.list();
if (remaining != null && remaining.length == 0) {
log.info("delete empty dir:{}", dir.getPath());
dir.delete();
}
} else {
//判斷時間
// 判断文件创建时间,超过保留天数则删除
BasicFileAttributes attr = null;
try {
Path path = dir.toPath();
attr = Files.readAttributes(path, BasicFileAttributes.class);
} catch (IOException e) {
e.printStackTrace();
log.warn("read file attributes failed: {}", dir.getPath(), e);
return;
}
// 创建时间
Instant instant = attr.creationTime().toInstant();
LocalDateTime createTime = LocalDateTime.ofInstant(instant, ZoneId.systemDefault());
Duration duration = Duration.between(createTime, now);
if (days <= duration.toDays()) {
log.info("delete path:{}",dir.getPath());
log.info("delete file:{}", dir.getPath());
dir.delete();
}
}

Loading…
Cancel
Save