public class DeleteFileJob {
public void deleteFile() {
Path path= Paths.get("C://");
SimpleFileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
@Override
//删除三天前的文件
public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
Date createTime = getCreateTime(file);
Date currentTime=DateUtils.addDays(new Date(),-3);
if(createTime!=null) {
if (createTime.compareTo(currentTime) < 0) {
Files.deleteIfExists(file);
}
}
return FileVisitResult.CONTINUE;
}
};
try {
//遍历目录进行删除
Files.walkFileTree(path,simpleFileVisitor);
} catch (IOException e) {
logger.error(e);
}
}
//获取文件创建时间
private static Date getCreateTime(Path path){
BasicFileAttributeView basicview= Files.getFileAttributeView(path, BasicFileAttributeView.class, LinkOption.NOFOLLOW_LINKS );
BasicFileAttributes attr;
try {
attr = basicview.readAttributes();
Date createDate = new Date(attr.creationTime().toMillis());
return createDate;
} catch (Exception e) {
logger.error(e);
}
return null;
}
}
NIO.2遍历目录删除指定日期前的文件
最新推荐文章于 2023-01-14 01:20:58 发布