0

I have developed an application which moves source file from source directory to target directory by using apache Fileutils class methods as shown below..

private void filemove(String FilePath2, String s2) { 

    String filetomove = FilePath2 + s2;    //file to move its complete path
    File f = new File(filetomove);
    File d = new File(targetFilePath); //    path of target directory 
    try {
        FileUtils.copyFileToDirectory(f, d);
        f.delete(); //from source dirrectory we are deleting the file if it succesfully move
    //*********** code need to add to delete the zip files of target directory and only keeping the latest two zip files  ************//        
    } catch (IOException e) {
        String errorMessage =  e.getMessage();
        logger.error(errorMessage);

    }

}

Now when I'm moving the file to the target directory, so in that case the target directory will be having certain zip files, what I am trying is that when ever I move my source file to target directory... it should do a pre-check such that in target directory it should delete all zip files but keeping only last 7 days zip files (so it should not delete last 7 day zip files)

What I have tried is working for last two days zip files that is it keeps recent two days zip files.

Please advise how can i change this in seven days such that it should keep last seven days zip files?
Take all the files in an array, and sort them, then just ignore the first two:

    Comparator<File> fileDateComparator = new Comparator<File>() {
        @Override
        public int compare(File o1, File o2) {
            if(null == o1 || null == o2){
                return 0;
            }
            return (int) (o2.lastModified() - o1.lastModified());//yes, casting to an int. I'm assuming the difference will be small enough to fit.
        }
    };

    File f = new File("/tmp");
    if (f.isDirectory()) {
        final File[] files = f.listFiles();
        List<File> fileList = Arrays.asList(files);
        Collections.sort(fileList, fileDateComparator);
        System.out.println(fileList);
    }
Tuna
  • 2,937
  • 4
  • 37
  • 61
tuntun wretee
  • 49
  • 1
  • 6

1 Answers1

2

Do you really need to sort and all? If you need to delete files which are more than 7 days old, get the lastModifieddate and substract it from current time. if the difference is more than 7*24*60*60 seconds then you can delete it.

All you need is a for loop after the f.listFiles() line. Not actual code - use to get to the working code.

long  timeInEpoch = System.currentTimeMillis(); // slightly faster than new Date().getTimeInMillis();
File f = new File("/tmp");
if (f.isDirectory()) {
    final File[] files = f.listFiles();
    for(int i =0; i < files.length ; i++ ) {
       if( timeInEpoch  - f.lastModifiedDate()  > 1000*60*60*24*7 )  
           files[i].delete();
    }
    System.out.println(fileList);
}
Menelaos
  • 23,508
  • 18
  • 90
  • 155
Akhilesh Singh
  • 2,548
  • 1
  • 13
  • 10