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