Delete files created more than 10 days ago, saving the most recent, if everyone on the list has more than 10 days of creation

4

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.     

asked by anonymous 17.08.2016 / 20:31

2 answers

7

Once you have the files in an array:

  • sort by descending order of modification date
  • Make sure the modification date of the first item is more than 10 days
    • If yes, scroll through the array from the second item and delete all files.
    • If not, go through the array and remove files with modification date greater than 10 days.

Use this comparator

public class LastModifiedFileDescendingComparator implements Comparator<File>{

    @Override
    public int compare(File file1, File file2) {
        long result = file1.lastModified() - file2.lastModified();
        if (result < 0) {
            return 1;
        } else if (result > 0) {
            return -1;
        } else {
            return 0;
        }
    }
}

like this:

Arrays.sort(array, new LastModifiedFileDescendingComparator());

Your code, using Array.sort() and the best way to calculate the cut-off date, will look like this:

public static void removeOldFiles() {

    long daysToMilliseconds = 24 * 60 * 60 * 1000;

    //resgato o limite de dias de um arquivo mas
    //estou trabalhando com diasLimite = 10
    Propriedade prop = new Propriedade();
    int limiteDays = Integer.valueOf(prop.getDbBackupDelLimit());
    long limiteTime = new Date().getTime() - limitDays * daysToMilliseconds;

    File bkpPasta = new File(prop.getDatabaseURL() + prop.getDbBackupDir());
        //listo os arquivos contidos
    File[] arqs = bkpPasta.listFiles();

    if (limitDays > 0 && arqs.length > 0) {

        //Ordeno os arquivos 
        Arrays.sort(arqs, new LastModifiedFileDescendingComparator());

        //Se o arquivo mais recente estiver dentro do limite, apago a partir do segundo.
        if(shouldDeleteFile(arqs[0], limiteTime)){
            deleteOldFiles(arqs, 1, limiteTime);
        }else{//se não apago a partir do primeiro
            deleteOldFiles(arqs, 0, limiteTime);
        }
    }

}

private void deleteOldFiles(File[] files, int first, long limitTime){
    for (int i = first; i < files.length; i++) {
        if(shouldDeleteFile(files[i], limitTime)){
            files[i].delete();
        }
    }

}
private boolean shouldDeleteFile(File file, long limitTime){
    return file.lastModified() < limitTime;
}

public class LastModifiedFileDescendingComparator implements Comparator<File>{

    @Override
    public int compare(File file1, File file2) {
        long result = file1.lastModified() - file2.lastModified();
        if (result < 0) {
            return 1;
        } else if (result > 0) {
            return -1;
        } else {
            return 0;
        }
    }
}

See, using auxiliary methods, the main method has been simple and easy to read.

Since removeOldFiles is responsible for getting the files to be deleted and being the backup files, I would change its name to removeOldBackupFiles .

    
18.08.2016 / 13:28
3

One option is to sort the list of files using the comparator:

import org.apache.commons.io.comparator.LastModifiedFileComparator;  

The function below sorts the array, then you can delete it from the second item.

File[] arqs = directory.listFiles();
Arrays.sort(arqs, LastModifiedFileComparator.LASTMODIFIED_COMPARATOR);
for (File file : arqs) {
    Date ultModificado = new Date(file.lastModified());        
}

Source: link

    
17.08.2016 / 20:48