delete Folder Content for older content - Android java.io

Android examples for java.io:Folder

Description

delete Folder Content for older content

Demo Code

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

public class Main {

  public static void deleteFolderContent(File directoryToBeDeleted, int daysToKeepFiles, boolean isRecursive) {

    Calendar limitCalendar = Calendar.getInstance();
    limitCalendar.add(Calendar.DAY_OF_YEAR, -1 * daysToKeepFiles);

    if (directoryToBeDeleted.isDirectory()) {
      String[] children = directoryToBeDeleted.list();
      for (int i = 0; i < children.length; i++) {

        File file = new File(directoryToBeDeleted, children[i]);

        if (isRecursive && file.isDirectory()) {
          deleteFolderContent(directoryToBeDeleted, daysToKeepFiles, isRecursive);
        } else {//from  www. ja va  2  s  .c  om

          Calendar fileCalendar = Calendar.getInstance();
          fileCalendar.setTimeInMillis(file.lastModified());

          if (daysToKeepFiles != -1) {
            if (limitCalendar.after(fileCalendar)) {
              file.delete();
            }
          } else {
            file.delete();
          }
        }
      }
    }
  }

}

Related Tutorials