Search code examples
javafilefile-management

Java Delete files older than N days


I would like some Java code to Delete files older than N days.

Here is my attempt, but it doesn't work quite right.

public void deleteFilesOlderThanNdays(final int daysBack, final String dirWay) {

    System.out.println(dirWay);
    System.out.println(daysBack);

    final File directory = new File(dirWay);
    if(directory.exists()){
        System.out.println(" Directory Exists");
        final File[] listFiles = directory.listFiles();          
        final long purgeTime = 
            System.currentTimeMillis() - (daysBack * 24 * 60 * 60 * 1000);

        System.out.println("System.currentTimeMillis " + 
            System.currentTimeMillis());

        System.out.println("purgeTime " + purgeTime);

        for(File listFile : listFiles) {
            System.out.println("Length : "+ listFiles.length);
            System.out.println("listFile.getName() : " +listFile.getName());
            System.out.println("listFile.lastModified() :"+
                listFile.lastModified());

            if(listFile.lastModified() < purgeTime) {
                System.out.println("Inside File Delete");
            }
        }
    } 
    else 
    {
    }
}

Is there some simple code to delete files older than N days in a directory?


Solution

  • Try to use the Calendar-Class instead:

     Calendar cal = Calendar.getInstance();  
     cal.add(Calendar.DAY_OF_MONTH, daysBack * -1);  
     long purgeTime = cal.getTimeInMillis();   
    

    Or try this solution:

    Is your number of days over 24? If so, you have an overflow problem.

    If the number of days is 25, the value will be:

    25 * 24 * 60 * 60 * 1000
    

    The mathematical value is 2160000000. However, this is larger than Integer.MAX_VALUE, and therefore the value overflows to -12516353. As a result, the purge time will be in the future, and will never be met. Values larger than 25 will only make the problem worse; it's even possible the overflow is so bad that the multiplication results in a positive value again leading to perhaps purge all files.

    The fix is easy:

    1. declare daysBack as a long
    2. cast daysBack to a long

      long purgeTime = System.currentTimeMillis() - ((long)daysBack * 24 * 60 * 60 * 1000);  
      
    3. Use explicit long literals inside the calculation:

      long purgeTime = System.currentTimeMillis() - (daysBack * 24L * 60L * 60L * 1000L); 
      

    For all three solutions, the fact that the first and/or second operand is a long turns the entire result into a long, allowing a value of 2160000000 without overflowing.