2

How can I delete all older files created till yesterday in directory (but not directory)?

I tried with this but unable to get delete files exists till yesterday.

for(File file: new File(strFile).listFiles()) 
      if (!file.isDirectory() && file.lastModified() < 1.0) 
         file.delete();
venkat
  • 5,648
  • 16
  • 58
  • 83

2 Answers2

1

First lastModified returns:

A long value representing the time the file was last modified, measured in milliseconds since the epoch (00:00:00 GMT, January 1, 1970), or 0L if the file does not exist or if an I/O error occurs

You need to get current time in milliseconds then subtract what last modified returns and the verify if it was modified before your target period. Or perform the time calculation in any type you desire.

Following your code:

    long day = 1000 * 60 * 60 * 24;
    long now = System.currentTimeMillis();
    for(File file: new File(DIRECTORY).listFiles()) 
          if (!file.isDirectory() && (now - file.lastModified() > day))
             file.delete();

Ideally you would be running this as an scheduled task

bichito
  • 1,406
  • 2
  • 19
  • 23
0

here is an example which deletes all temp files more than a day old:

import org.apache.commons.lang3.Validate;

import java.io.File;
import java.util.Arrays;
import java.util.Calendar;
import java.util.Date;

public class StackOverflow44850006 {
  /**
   * deletes all the files in a directory modified before a given timestamp
   *
   * @param directoryPath path to delete from
   * @param stamp         everything with a mod date before this timestamp will  be deleted
   * @return the number of items deleted
   */
  public static long deleteOld(final String directoryPath, final Date stamp) {
    final File[] files = new File(directoryPath).listFiles();
    Validate.notNull(files, "Unable to open dir. Does it exist?");
    return Arrays.stream(files)
        .filter(f -> !f.isDirectory())
        .filter(f -> f.lastModified() < stamp.getTime())
        .map(File::delete)
        .filter(Boolean::booleanValue)
        .count();
  }

  public static void main(String[] args) {
    final String tempDir = System.getProperty("java.io.tmpdir");
    final Calendar yesterday = Calendar.getInstance();
    yesterday.add(Calendar.DATE, -1);
    System.out.println(deleteOld(tempDir, yesterday.getTime()));
  }
}
Andreas
  • 4,937
  • 2
  • 25
  • 35