2
I am trying to automate the deletion of some backup files that a small application I made in swing creates, which over time, accumulates, occupying too much space in the network directory, which already has a storage limit. The list of files is in this layout:
I tried to do the method below, and until I get the difference of dates by taking the modification date provided by windows comparing with a manually informed date, as code below:
public class RemoveOldFilesDB {
public static void main(String[] args) {
try {
//aqui eu pego de outro arquivo o link do diretorio,
//está funcionando corretamente
Propriedade prop = new Propriedade();
File bkpPasta = new File(prop.getDatabaseURL() + prop.getDbBackupDir());
File[] arqs = bkpPasta.listFiles();
Date limit = new SimpleDateFormat("dd/MM/yyyy").parse("10/06/2016");
int contador = 0;
for (File f : arqs) {
//f.delete();
Date lastModified = new Date(f.lastModified());
if (lastModified.before(limit)) {
contador++;
}
}
System.out.println(contador + " arquivos foram criados há mais de 10 dias atrás.");
} catch (ParseException | IOException ex) {
ex.printStackTrace();
}
}
}
The code (made for testing), counts the number of files in the list that were created on time, and returns me correctly:
9 files were created more than 10 days ago.
However I’m not sure how to define this day difference to play on limit
.
How to calculate this difference from the current date so that deletion is done only in files that were created before the due date?
Note: I cannot use Jodatime because the application was made on top of JDK7.
GregorianCalendar gc = new GregorianCalendar();
gc.setTime(date);
gc.set(Calendar.DATE, gc.get(Calendar.DATE) - 10);
Date limit = gc.getTime().DATE;
– Marco Souza
What does JDK 7 have to do with Jodatime?
– Pablo Almeida
@Pabloalmeida to use the jodatime in jdk 7 I would have to add lib to the part in the classpath, and I can’t do that. On the other hand, JDK 8 has an equivalent (or the same, I can’t say) in the native java.time package
– user28595
I wanted to answer, but I can’t test my hahaha +1 code
– Renan Gomes
@When you give, put your suggestion there, these Date classes are a headache to manipulate hehe
– user28595