-1

I am creating a backup logic wherein I am copying a file from source folder to destination folder(backup). My requirement is I should only store 2 latest files in my destination folder.

I am trying to use the file.lastModified() but I am not sure how.

Anthon
  • 69,918
  • 32
  • 186
  • 246
Angel
  • 9
  • 1
  • Are you doing backup for only one file , say a.txt or do you have multiple files to do backup – Abhi Jun 09 '15 at 19:20
  • Source folder has 1 file only and my destination should only contain 2 files which is from previous backup – Angel Jun 09 '15 at 19:30

2 Answers2

0

I think I managed to solve my problem. Here is what I did. Please let me know if there is better way to do this. Thanks!

FileUtils.copyDirectory(source, dest);

long lastModified = 0;
    if(Util.hasData(dest.listFiles())){
        File[] fileList = dest.listFiles();         

        for(File file: fileList){
            if(lastModified != 0 ){
                if(lastModified > file.lastModified()){
                    lastModified = file.lastModified();
                }
            }else {
                lastModified = file.lastModified();
            }
        }
        if (dest.listFiles().length >= 2) {
            for (File file : fileList) {
                if (file.lastModified() == lastModified) {                      
                    file.delete();
                }
            }
        }


    }
Angel
  • 9
  • 1
  • Take a look at the LastModifiedFileComparator library. This So answer may help http://stackoverflow.com/questions/203030/best-way-to-list-files-in-java-sorted-by-date-modified – Abhi Jun 09 '15 at 19:42
  • Thank you very much! This is helpful – Angel Jun 09 '15 at 19:56
0

[yourfile].lastModified() will return the date that the file was last changed in milliseconds. Therefore, the bigger the number it is, the more recently the file was edited. Using this you can simply run through each file in your folder, and determine which were the most recent two. Something like this should work:

ArrayList<File> files = new ArrayList<>(); //pretend this is all the files in your folder

long[] timemodified = new long[files.length];
long recentone = 1; //temporarly stores the time of the most recent file
long recenttwo = 0;
File mostrecentone = null;
File mostrecenttwo = null;

for(File f : files){           //for each file in the arraylist
long tm = f.lastModified();    //get the time this file was last modified
    if(tm > recentone){        //if it is more recent than the current most recent file
        recentone = tm;        //set the current most recent file time to be this
        mostrecentone = f;     //set the current most recent file to be f
    }else if(tm > mostrecenttwo){
        recenttwo = tm;
        mostrecenttwo = f;
    }else{
        f.delete();
    }
}

Im pretty sure that will work, all you need to do is put all the files in your folder into that ArrayList.