I have tried with how to retain files based on n number of days. This is the logic to do so.
public static void purgeFiles(int daysToRetain, String directory){
File backupDir = new File(directory);
long purgeTime = System.currentTimeMillis() - (daysToRetain * 24L * 60L * 60L * 1000L);
if(backupDir.exists()){
File[] listOfBackupFiles = backupDir.listFiles();
for(File backupFile : listOfBackupFiles){
if(backupFile.lastModified() < purgeTime){
if(backupFile.isFile()){
System.out.println(backupFile.getName()+" is going to delete");
backupFile.delete();
}
}
}
}
}
Here I have a doubt that how to retain latest 10 files in a directory. File creation date and times are different.
There is no fixed time to create files. Files will not get create daily or weekly or monthly. One file will get create in 2 days, others will be in 5 days.
So, I want to retain latest 10 files.