Delete files created before 10 days ago from current date

Asked

Viewed 804 times

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:

lista de arquivos com data de modificação

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;

  • What does JDK 7 have to do with Jodatime?

  • @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

  • 1

    I wanted to answer, but I can’t test my hahaha +1 code

  • @When you give, put your suggestion there, these Date classes are a headache to manipulate hehe

1 answer

2


I don’t 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();
        }
    }
}
  • It worked as expected, thank you :) For the reply to be complete, you can add these comments directly in the code?

Browser other questions tagged

You are not signed in. Login or sign up in order to post.