Search code examples
javaarraysfilesorting

How to get oldest file in a directory using Java


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:

  • Get the list of files using the File.listFiles() method
  • Loop through each File
  • Store the last modified date using File.lastModified() and compare with File from loop iteration, keep the oldest lastModified()

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


Solution

  • 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();
            }
        }
    }