[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
.