删除某目录下n天之前的文件

功能:删除N天之前的文件
import java.io.File;
import java.util.Date;
import java.util.Iterator;

import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.FileFileFilter;
import org.apache.commons.io.filefilter.FileFilterUtils;
import org.apache.commons.io.filefilter.IOFileFilter;
import org.apache.commons.io.filefilter.TrueFileFilter;

public class FileTools
{
    public static void deleteFiles(String dirPath, int days)
    {
        
        // 计算备份日期,备份该日期之前的文件
        Date pointDate = new Date();
        long timeInterval = pointDate.getTime() - convertDaysToMilliseconds(days);
        pointDate.setTime(timeInterval);
        
        // 设置文件过滤条件
        IOFileFilter timeFileFilter = FileFilterUtils.ageFileFilter(pointDate, true);
        IOFileFilter fileFiles = FileFilterUtils.andFileFilter(FileFileFilter.FILE, timeFileFilter);
        
        // 删除符合条件的文件
        File deleteRootFolder = new File(dirPath);
        Iterator itFile = FileUtils.iterateFiles(deleteRootFolder, fileFiles, TrueFileFilter.INSTANCE);
        while (itFile.hasNext())
        {
            File file = (File)itFile.next();
            file.delete();
            
        }
        
    }
    
    /**
     * 天与毫秒的转换
     * 
     * @param days
     * @return
     */
    private static long convertDaysToMilliseconds(int days)
    {
        return days * 24L * 3600 * 1000;
    }
    
    public static void main(String[] args)
    {
        FileTools.deleteFiles("D:\\delete_file", 1);
    }
}


你可能感兴趣的:(java基础)