Are there any methods for obtaining the oldest file in a directory using java? I have a directory i write log files to and would like to delete log files after ive recorded over 500 log files (but only want to delete the oldest ones).
The only way i could conceive myself is:
The inconvenient aspect of this logic is that i would have to loop the log directory every time i want to get the oldest files and that does not seem the most efficient.
i expected the java.io.File library would have a method to get the oldest file in a directory but it doesnt seem to exist, or i havent found it. If there is a method for obtaining the oldest file in a directory or a more convenient approach in programming the solution, i would love to know.
Thanks
Based off of @Yoda comment, i figured i would answer my own question.
public static void main(String[] args) throws IOException {
File directory = new File("/logFiles");
purgeLogFiles(directory);
}
public void purgeLogFiles(File logDir){
File[] logFiles = logDir.listFiles();
long oldestDate = Long.MAX_VALUE;
File oldestFile = null;
if( logFiles != null && logFiles.length >499){
//delete oldest files after theres more than 500 log files
for(File f: logFiles){
if(f.lastModified() < oldestDate){
oldestDate = f.lastModified();
oldestFile = f;
}
}
if(oldestFile != null){
oldestFile.delete();
}
}
}