Delete files created before 10 days ago from the current date

3

I'm trying to automate the deletion of some backup files that a small application I've made in swing creates, which over time will accumulate, taking up too much space in the network directory, which already has a storage limit. The list of files is in this arrangement:

Itriedtodothemethodbelow,anduntilIgetthedifferenceofdatestakingthemodificationdateprovidedbywindowscomparingwithamanuallyentereddate,asbelowcode:

publicclassRemoveOldFilesDB{publicstaticvoidmain(String[]args){try{//aquieupegodeoutroarquivoolinkdodiretorio,//estáfuncionandocorretamentePropriedadeprop=newPropriedade();FilebkpPasta=newFile(prop.getDatabaseURL()+prop.getDbBackupDir());File[]arqs=bkpPasta.listFiles();Datelimit=newSimpleDateFormat("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 (I did for test), 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.

But I'm not sure how I'll define this difference of days from the current date to play in limit .

How to calculate this difference from the current date so that the deletion is only made to files that were created before the due date?

Note: I can not use JodaTime because the application was made on JDK7.

asked by anonymous 20.06.2016 / 17:38

1 answer

3

I do not know if it's the best way, but I use the method below:

public static void deletarArquivos(int qtdDias, String path) {
    Date data = new Date();
    Calendar c = Calendar.getInstance();//obtendo a instancia do Calender
    c.setTime(data);////setando a data atual
    c.add(Calendar.DATE, -qtdDias);//removendo a quantidade de dias
    data = c.getTime();//obtendo a data alterada

    File arquivos = new File(path);//instanciando o caminho dos arquivos
    String[] nomes = arquivos.list();
    for (String nome : nomes) {
        File temp = new File(arquivos.getPath(), nome);
        Date arquivo = new Date(temp.lastModified());
        if (arquivo.before(data)) {
            temp.delete();
        }
    }
}
    
20.06.2016 / 19:48