I have created list of files to store some attribute after they are opened once in my app. Every time the file is opened those attributes are changed so I made them be deleted and created again.
I have created all the files 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 those files here older than a week as those stored attributes won't be required any more. What'd be the appropriate method to do so?
Using the find command, you can search for and delete all files that have been modified more than X days. Also, if required you can delete them with a single command. First of all, list all files older than 30 days under /opt/backup directory.
-mtime +30 : This refers to all the files which are older than 30 days. mtime stands for Modification time in Unix. You can change the number based on your requirement. -exec rm {} \ : This is actually the execution command which calls for deletion of all the files filtered by all the above criteria.
This should do the trick. It will create a calendar instance to 7 days ago and compare if the modified date of the file is before that time. If it is that means that 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 dir you can use this and then iterate 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;
}
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
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With