Delete files older than x days

2019-01-17 14:49发布

How can I find out when a file was created using java, as I wish to delete files older than a certain time period, currently I am deleting all files in a directory, but this is not ideal:

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();
    }
}

Above is my current code, I am trying now to add an if statement in that will only delete files older than say a week.

EDIT:

@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();
        }
    }

Adding a loop now.

EDIT

I have noticed while testing the code above I get the last modified in :

INFO: Date Modified : 1361635382096

How should I code the if loop to say if it is older than 7 days delete it when it is in the above format?

13条回答
Explosion°爆炸
2楼-- · 2019-01-17 15:02

You can get the creation date of the file using NIO, following is the way:

BasicFileAttributes attrs = Files.readAttributes(file, BasicFileAttributes.class);
System.out.println("creationTime: " + attrs.creationTime());

More about it can be found here : http://docs.oracle.com/javase/tutorial/essential/io/fileAttr.html

查看更多
Ridiculous、
3楼-- · 2019-01-17 15:05

Another approach with Apache commons-io and joda:

private void deleteOldFiles(String dir, int daysToRemainFiles) {
    Collection<File> filesToDelete = FileUtils.listFiles(new File(dir),
            new AgeFileFilter(DateTime.now().withTimeAtStartOfDay().minusDays(daysToRemainFiles).toDate()),
            TrueFileFilter.TRUE);    // include sub dirs
    for (File file : filesToDelete) {
        boolean success = FileUtils.deleteQuietly(file);
        if (!success) {
            // log...
        }
    }
}
查看更多
甜甜的少女心
4楼-- · 2019-01-17 15:05

Using Java NIO Files with lambdas & Commons IO

final long time = new Date().getTime();
// Only show files & directories older than 2 days
final long maxdiff = TimeUnit.DAYS.toMillis(2);

List all found files and directories:

Files.newDirectoryStream(Paths.get("."), p -> (time - p.toFile().lastModified()) < maxdiff)
.forEach(System.out::println);

Or delete found files with FileUtils:

Files.newDirectoryStream(Paths.get("."), p -> (time - p.toFile().lastModified()) < maxdiff)
.forEach(p -> FileUtils.deleteQuietly(p.toFile()));
查看更多
太酷不给撩
5楼-- · 2019-01-17 15:09

Using Apache commons-io and joda:

        if ( FileUtils.isFileOlder(f, DateTime.now().minusDays(30).toDate()) ) {
            f.delete();
        }
查看更多
6楼-- · 2019-01-17 15:13

Here's Java 8 version using Time API. It's been tested and used in our project:

    public static int deleteFiles(final Path destination,
        final Integer daysToKeep) throws IOException {

    final Instant retentionFilePeriod = ZonedDateTime.now()
            .minusDays(daysToKeep).toInstant();

    final AtomicInteger countDeletedFiles = new AtomicInteger();
    Files.find(destination, 1,
            (path, basicFileAttrs) -> basicFileAttrs.lastModifiedTime()
                    .toInstant().isBefore(retentionFilePeriod))
            .forEach(fileToDelete -> {
                try {
                    if (!Files.isDirectory(fileToDelete)) {
                        Files.delete(fileToDelete);
                        countDeletedFiles.incrementAndGet();
                    }
                } catch (IOException e) {
                    throw new UncheckedIOException(e);
                }
            });

    return countDeletedFiles.get();
}
查看更多
聊天终结者
7楼-- · 2019-01-17 15:15

Commons IO has built-in support for filtering files by age with its AgeFileFilter. Your DeleteFiles could just look like this:

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();
    }
}

Update: To use the value as given in your edit, define the thresholdDate as:

Date tresholdDate = new Date(1361635382096L);
查看更多
登录 后发表回答