Delete Files Older than n number Of days Using Java

 Posted On  | Yashwant Chavan 

Some times in application development, we required to delete files older than specified number of days. Actually this is clean up utility which removes older files from disk and free the hard disk memory.

Below example demonstrate how to delete files, older than specified number of days. This code delete files from specified directory only, not from child folders. delete() method takes two parameters first one is number of days and second parameter is file extension. It delete only specified extension files.

listFile.lastModified() - Returns the last modified time in milliseconds.

DeleteFiles.java

package com.technicalkeeda.app;

import java.io.File;

public class DeleteFiles {

    private String dirPath = "c:\\hello";

    public static void main(String[] args) {
        DeleteFiles deleteFiles = new DeleteFiles();
        deleteFiles.delete(5, ".jpg");
    }

    public void delete(long days, String fileExtension) {

        File folder = new File(dirPath);

        if (folder.exists()) {

            File[] listFiles = folder.listFiles();

            long eligibleForDeletion = System.currentTimeMillis() -
                (days * 24 * 60 * 60 * 1000 L);

            for (File listFile: listFiles) {

                if (listFile.getName().endsWith(fileExtension) &&
                    listFile.lastModified() < eligibleForDeletion) {

                    if (!listFile.delete()) {

                        System.out.println("Sorry Unable to Delete Files..");

                    }
                }
            }
        }
    }
}  


Promote your Blog, Website, or services on technicalkeeda.com, My paypal id: yashwantchavan@gmail.com

Payment will be accepted through paypal only.


© technicalkeeda.com 2017

 |  Find us on Google+ |  Rss Feed

Loaded in 0.0258 seconds.