That should do the trick. It will create a calendar instance up to 7 days ago and compare if the file date has been changed before that time. If that means the file is older than 7 days.
if(file.exists()){ Calendar time = Calendar.getInstance(); time.add(Calendar.DAY_OF_YEAR,-7); //I store the required attributes here and delete them Date lastModified = new Date(file.lastModified()); if(lastModified.before(time.getTime())) { //file is older than a week } file.delete(); }else{ file.createNewFile(); }
If you want to get all the files in a directory, you can use it and then repeat the result and compare each file.
public static ArrayList<File> getAllFilesInDir(File dir) { if (dir == null) return null; ArrayList<File> files = new ArrayList<File>(); Stack<File> dirlist = new Stack<File>(); dirlist.clear(); dirlist.push(dir); while (!dirlist.isEmpty()) { File dirCurrent = dirlist.pop(); File[] fileList = dirCurrent.listFiles(); for (File aFileList : fileList) { if (aFileList.isDirectory()) dirlist.push(aFileList); else files.add(aFileList); } } return files; }
source share