定时清理文件及文件夹

import java.io.File;
import java.io.IOException;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
import java.nio.file.attribute.FileTime;
import java.util.Date;

import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.ioif.util.Configer;
import com.ioif.util.Logger;

/**
* 清理临时文件
*
* @author lch
* @date 2021年8月11日
*/
@Component
public class ClearTempFilesTask {

//临时文件保存时间30天
private final Long SAVE_TIME = 1000 * 60 * 60 * 24 * 30L;

/**
* 每天执行一次
*/
@Scheduled(cron = "0 0 0 * * ?")
public void runTask() {
Logger.getLogger().info(this.getClass().getName() + ":runTask()");
try {
//临时文件目录
String filePath = Configer.getInstance().getProperty("temp_file_write");
delFiles(filePath);
} catch (Exception e) {
Logger.getLogger().error(e.getMessage());
e.printStackTrace();
}
}

private void delFiles(String filePath) {
Long now=new Date().getTime();
File directory = new File(filePath);
if (directory.exists()) {
String[] fileList = directory.list();
File tmpFile = null;
for (int i = 0; i < fileList.length; i++) {
tmpFile = new File(directory.getAbsolutePath(), fileList[i]);
if (tmpFile.isDirectory()) {
delFiles(tmpFile.getPath());
if(new File(directory.getAbsolutePath(), fileList[i]).list().length<1){
new File(directory.getAbsolutePath(), fileList[i]).delete();
}
} else if (tmpFile.isFile()) {
try {
BasicFileAttributes bAttributes= Files.readAttributes(tmpFile.toPath(),BasicFileAttributes.class);
FileTime ct = bAttributes.lastModifiedTime();
if(now-ct.toMillis()>SAVE_TIME)
tmpFile.delete();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}

public static void main(String[] args) {
ClearTempFilesTask task = new ClearTempFilesTask();
task.runTask();
}

}
posted @ 2021-08-11 11:39  Zz~  阅读(173)  评论(0编辑  收藏  举报