I did this question where the question was how to delete files with more than 10 days of creation. I retrieve them from a directory and the code has already been implemented and is functional.
However, I ended up with a problem that could cause the code to erase all the files, if the program stays 10 days without being executed. I need to save the latest file if this occurs, but as I do not know in which order java retrieves this list from windows, I can not consider that the last one (or the first ad list) would be the most recent.
How do I save the most recent file while retaining the code exclusion structure below? Preferably using native java resources , as I have some limitations that can cause me problems if I add external libs.
public static void removeOldFiles() {
try {
//resgato o limite de dias de um arquivo mas
//estou trabalhando com diasLimite = 10
Propriedade prop = new Propriedade();
int diasLimite = Integer.valueOf(prop.getDbBackupDelLimit());
if (diasLimite > 0) {
Date data = new Date();
Calendar c = Calendar.getInstance();
c.setTime(data);
//seta a data limite de criação
//dos backups antigos
c.add(Calendar.DATE, - diasLimite);
Date limit = c.getTime();
//pego a URL da pasta
File bkpPasta = new File(prop.getDatabaseURL() + prop.getDbBackupDir());
//listo os arquivos contidos
File[] arqs = bkpPasta.listFiles();
for (File f : arqs) {
//pego a data de ultima modificacao
//para checar se tem mais de 10 dias
Date lastModified = new Date(f.lastModified());
if (lastModified.before(limit)) {
f.delete();
}
}
}
} catch (IOException ex) {
ex.printStackTrace();
}
}
Note: Unfortunately I can not use java 8 resources, because the application was made on JDK7.