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条回答
虎瘦雄心在
2楼-- · 2019-01-17 15:18

You can use File.lastModified() to get the last modified time of a file/directory.

Can be used like this:

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

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

Which deletes files older than x (an int) days.

查看更多
爷、活的狠高调
3楼-- · 2019-01-17 15:22

Here is the code to delete files which are not modified since six months & also create the log file.

package deleteFiles;

import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Calendar;
import java.util.Date;
import java.util.logging.FileHandler;
import java.util.logging.Logger;
import java.util.logging.SimpleFormatter;

public class Delete {
    public static void deleteFiles()
    {
        int numOfMonths = -6;
        String path="G:\\Files";
        File file = new File(path);
        FileHandler fh;
        Calendar sixMonthAgo = Calendar.getInstance();
        Calendar currentDate = Calendar.getInstance();
        Logger logger = Logger.getLogger("MyLog");
        sixMonthAgo.add(Calendar.MONTH, numOfMonths);
        File[] files = file.listFiles();
        ArrayList<String> arrlist = new ArrayList<String>();

        try {
            fh = new FileHandler("G:\\Files\\logFile\\MyLogForDeletedFile.log");
            logger.addHandler(fh);
            SimpleFormatter formatter = new SimpleFormatter();
            fh.setFormatter(formatter);

            for (File f:files)
            {
                if (f.isFile() && f.exists())
                {
                    Date lastModDate = new Date(f.lastModified());
                    if(lastModDate.before(sixMonthAgo.getTime()))
                    {
                        arrlist.add(f.getName());
                        f.delete();
                    }
                }
            }
            for(int i=0;i<arrlist.size();i++)
                logger.info("deleted files are ===>"+arrlist.get(i));
        }
        catch ( Exception e ){
            e.printStackTrace();
            logger.info("error is-->"+e);
        }
    }
    public static void main(String[] args)
    {
        deleteFiles();
    }
}
查看更多
Juvenile、少年°
4楼-- · 2019-01-17 15:25

Need to point out a bug on the first solution listed, x * 24 * 60 * 60 * 1000 will max out int value if x is big. So need to cast it to long value

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

if (diff > (long) x * 24 * 60 * 60 * 1000) {
    file.delete();
}
查看更多
走好不送
5楼-- · 2019-01-17 15:26

Using Apache utils is probably the easiest. Here is the simplest solution I could come up with.

public void deleteOldFiles() {
    Date oldestAllowedFileDate = DateUtils.addDays(new Date(), -3); //minus days from current date
    File targetDir = new File("C:\\TEMP\\archive\\");
    Iterator<File> filesToDelete = FileUtils.iterateFiles(targetDir, new AgeFileFilter(oldestAllowedFileDate), null);
    //if deleting subdirs, replace null above with TrueFileFilter.INSTANCE
    while (filesToDelete.hasNext()) {
        FileUtils.deleteQuietly(filesToDelete.next());
    }  //I don't want an exception if a file is not deleted. Otherwise use filesToDelete.next().delete() in a try/catch
}
查看更多
姐就是有狂的资本
6楼-- · 2019-01-17 15:27

For a JDK 8 solution using both NIO file streams and JSR-310

long cut = LocalDateTime.now().minusWeeks(1).toEpochSecond(ZoneOffset.UTC);
Path path = Paths.get("/path/to/delete");
Files.list(path)
        .filter(n -> {
            try {
                return Files.getLastModifiedTime(n)
                        .to(TimeUnit.SECONDS) < cut;
            } catch (IOException ex) {
                //handle exception
                return false;
            }
        })
        .forEach(n -> {
            try {
                Files.delete(n);
            } catch (IOException ex) {
                //handle exception
            }
        });

The sucky thing here is the need for handling exceptions within each lambda. It would have been great for the API to have UncheckedIOException overloads for each IO method. With helpers to do this one could write:

public static void main(String[] args) throws IOException {
    long cut = LocalDateTime.now().minusWeeks(1).toEpochSecond(ZoneOffset.UTC);
    Path path = Paths.get("/path/to/delete");
    Files.list(path)
            .filter(n -> Files2.getLastModifiedTimeUnchecked(n)
                    .to(TimeUnit.SECONDS) < cut)
            .forEach(n -> {
                System.out.println(n);
                Files2.delete(n, (t, u)
                              -> System.err.format("Couldn't delete %s%n",
                                                   t, u.getMessage())
                );
            });
}


private static final class Files2 {

    public static FileTime getLastModifiedTimeUnchecked(Path path,
            LinkOption... options)
            throws UncheckedIOException {
        try {
            return Files.getLastModifiedTime(path, options);
        } catch (IOException ex) {
            throw new UncheckedIOException(ex);
        }
    }

    public static void delete(Path path, BiConsumer<Path, Exception> e) {
        try {
            Files.delete(path);
        } catch (IOException ex) {
            e.accept(path, ex);
        }
    }

}
查看更多
啃猪蹄的小仙女
7楼-- · 2019-01-17 15:28

Using lambdas (Java 8+)

Non recursive option to delete all files in current folder that are older than N days (ignores sub folders):

public static void deleteFilesOlderThanNDays(int days, String dirPath) throws IOException {
    long cutOff = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000);
    Files.list(Paths.get(dirPath))
    .filter(path -> {
        try {
            return Files.isRegularFile(path) && Files.getLastModifiedTime(path).to(TimeUnit.MILLISECONDS) < cutOff;
        } catch (IOException ex) {
            // log here and move on
            return false;
        }
    })
    .forEach(path -> {
        try {
            Files.delete(path);
        } catch (IOException ex) {
            // log here and move on
        }
    });
}

Recursive option, that traverses sub-folders and deletes all files that are older than N days:

public static void recursiveDeleteFilesOlderThanNDays(int days, String dirPath) throws IOException {
    long cutOff = System.currentTimeMillis() - (days * 24 * 60 * 60 * 1000);
    Files.list(Paths.get(dirPath))
    .forEach(path -> {
        if (Files.isDirectory(path)) {
            try {
                recursiveDeleteFilesOlderThanNDays(days, path.toString());
            } catch (IOException e) {
                // log here and move on
            }
        } else {
            try {
                if (Files.getLastModifiedTime(path).to(TimeUnit.MILLISECONDS) < cutOff) {
                    Files.delete(path);
                }
            } catch (IOException ex) {
                // log here and move on
            }
        }
    });
}
查看更多
登录 后发表回答