Delete files older than a specified time from the directory

I created a list of files to store some attribute after it opens once in my application. Each time a file is opened, these attributes change, so I deleted and created them again.

I created all the files using

File file =new File(getExternalFilesDir(null), currentFileId+""); if(file.exists()){ //I store the required attributes here and delete them file.delete(); }else{ file.createNewFile(); } 

I want to delete all of these files here older than a week, since these stored attributes are no longer required. What would be the appropriate method?

+6
source share
3 answers

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; } 
+14
source
 if (file.exists()) { Date today = new Date(); int diffInDays = (int)( (today.getTime() - file.lastModified()) /(1000 * 60 * 60 * 24) ); if(diffInDays>7){ System.out.println("File is one week old"); //you can delete the file here } } 
+2
source

File.lastModified () returns long Int in Unix Time

0
source

Source: https://habr.com/ru/post/975185/


All Articles