Delete files older than N days in Java

Delete files older than some days is the process of cleaning up the hard disk memory. Generally deleting files used in application development.

In this tutorial, we are going to learn how to delete files older than N days using Java programming.

We are using the File class which will operate with files in Java.


  1. Create a class
  2. Create a main method
  3. In the main method, create an object of that class.
  4. In the same class, create another method that will delete files and will take 2 arguments (no. of days, extension) and write code accordingly
  5. By calling that method in main, we can delete

Create a class:

public class Deletefiles{

In that class create the main method and object of that class inside the main method. Enter parameters – no. of days and extension of files which we want to delete.

public class Deletefiles {
     public static void main(String[] args) {
        Deletefiles deleteFiles = new Deletefiles();
        deleteFiles.delete(4, ".pdf");

Now, from which directory it will delete files? For that create a private Instance variable inside the class and assign a path or directory.

Now, create a method in the same class.

public void delete(long nday, String extension) {
        File fold = new File(dirPath);
        if (fold.exists()) {
            File[] listAllFiles = folder.listAllFiles();
            long Deletion = System.currentTimeMillis() -
                (nday * 24 * 60 * 60 * 1000 L);
            for (File listFile: listAllFiles) {
                if (listFile.getName().endsWith(extension) &&
                    listFile.lastModified() < Deletion) {
                    if (!listFile.delete()) {
                        System.out.println("Sorry can't delete");

Now first, we have created an object for getting the path. If that path exists then only it will enter the loop. If yes then it is creating an array to store all the files in that array. Suppose you want to modify a file that is older than the days we are deleting files, so the code will delete it too. For that we are comparing modification time and based on that we are deleting them. The formula is given below:

System.currentTimeMillis() – (nday * 24 * 60 * 60 * 1000 L)

Thank you.

One response to “Delete files older than N days in Java”

  1. Manish says:

    It’s working fine and I implemented in my project within 1 hr

Leave a Reply

Your email address will not be published. Required fields are marked *