Delete older files in a directory until only those matching the given constraints remain. - Android java.io

Android examples for java.io:File Delete

Description

Delete older files in a directory until only those matching the given constraints remain.

Demo Code

import java.io.File;
import java.util.Arrays;
import java.util.Comparator;


public class Main {

  /**//  w  w w  . ja  va2 s . com
   * Delete older files in a directory until only those matching the given
   * constraints remain.
   *
   * @param minCount
   *          Always keep at least this many files.
   * @param minAge
   *          Always keep files younger than this age.
   * @return if any files were deleted.
   */
  public static boolean deleteOlderFiles(File dir, int minCount, long minAge) {
    if (minCount < 0 || minAge < 0) {
      throw new IllegalArgumentException("Constraints must be positive or 0");
    }

    final File[] files = dir.listFiles();
    if (files == null)
      return false;

    // Sort with newest files first
    Arrays.sort(files, new Comparator<File>() {
      @Override
      public int compare(File lhs, File rhs) {
        return (int) (rhs.lastModified() - lhs.lastModified());
      }
    });

    // Keep at least minCount files
    boolean deleted = false;
    for (int i = minCount; i < files.length; i++) {
      final File file = files[i];

      // Keep files newer than minAge
      final long age = System.currentTimeMillis() - file.lastModified();
      if (age > minAge) {
        if (file.delete()) {
          deleted = true;
        }
      }
    }
    return deleted;
  }

}

Related Tutorials