NIO.2遍历目录删除指定日期前的文件

public class DeleteFileJob {

    public void deleteFile() {
        Path path= Paths.get("C://");
        SimpleFileVisitor simpleFileVisitor = new SimpleFileVisitor() {
            @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;
    }

}

你可能感兴趣的:(工具代码积累)