Question:
How can files be listed in a directory, sorted by the oldest files first?
Discussion:
The standard approach is to utilize the File.listFiles() method to retrieve an array of files within a directory. However, the documentation emphasizes that this method provides no guarantees regarding the order of the returned files. To address this, many resort to manually sorting the array based on the File.lastModified() timestamp.
Optimal Solution:
The suggested solution employs an anonymous Comparator within the Arrays.sort() method, comparing files based on their last modified timestamps. Below is the updated code snippet:
File[] files = directory.listFiles(); Arrays.sort(files, new Comparator<File>() { public int compare(File f1, File f2) { return Long.valueOf(f1.lastModified()).compareTo(f2.lastModified()); } });
The above is the detailed content of How to Sort Files in a Java Directory by Modification Date (Oldest First)?. For more information, please follow other related articles on the PHP Chinese website!