删除早于 x 天的文件

2022-09-01 01:12:58

我怎么能找出一个文件是使用java创建的,因为我希望删除超过某个时间段的文件,目前我正在删除目录中的所有文件,但这并不理想:

public void DeleteFiles() {
    File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
    System.out.println("Called deleteFiles");
    DeleteFiles(file);
    File file2 = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/");
    DeleteFilesNonPdf(file2);
}

public void DeleteFiles(File file) {
    System.out.println("Now will search folders and delete files,");
    if (file.isDirectory()) {
        for (File f : file.listFiles()) {
            DeleteFiles(f);
        }
    } else {
        file.delete();
    }
}

以上是我当前的代码,我现在正试图添加一个if语句,该语句只会删除超过一周的文件。

编辑:

@ViewScoped
@ManagedBean
public class Delete {

    public void DeleteFiles() {
        File file = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/web/resources/pdf/");
        System.out.println("Called deleteFiles");
        DeleteFiles(file);
        File file2 = new File("D:/Documents/NetBeansProjects/printing~subversion/fileupload/Uploaded/");
        DeleteFilesNonPdf(file2);
    }

    public void DeleteFiles(File file) {
        System.out.println("Now will search folders and delete files,");
        if (file.isDirectory()) {
            System.out.println("Date Modified : " + file.lastModified());
            for (File f : file.listFiles()) {
                DeleteFiles(f);
            }
        } else {
            file.delete();
        }
    }

立即添加循环。

编辑

我注意到在测试上面的代码时,我得到了最后修改:

INFO: Date Modified : 1361635382096

我应该如何编写if循环,说如果它超过7天,请以上述格式删除它?


答案 1

您可以使用 File.lastModified() 来获取文件/目录的上次修改时间。

可以这样使用:

long diff = new Date().getTime() - file.lastModified();

if (diff > x * 24 * 60 * 60 * 1000) {
    file.delete();
}

这将删除早于 (a) 天的文件。xint


答案 2

Commons IO内置了对按年龄过滤文件的支持,其AgeFileFilter。你的可能看起来像这样:DeleteFiles

import java.io.File;
import org.apache.commons.io.FileUtils;
import org.apache.commons.io.filefilter.AgeFileFilter;
import static org.apache.commons.io.filefilter.TrueFileFilter.TRUE;

// a Date defined somewhere for the cutoff date
Date thresholdDate = <the oldest age you want to keep>;

public void DeleteFiles(File file) {
    Iterator<File> filesToDelete =
        FileUtils.iterateFiles(file, new AgeFileFilter(thresholdDate), TRUE);
    for (File aFile : filesToDelete) {
        aFile.delete();
    }
}

更新:要使用编辑中给定的值,请将thresholdDate

Date tresholdDate = new Date(1361635382096L);

推荐