Home >Java >javaTutorial >How Can I Get a Date-Sorted List of Files in Java?
Getting a Date-Sorted File List in Java
To retrieve a list of files in a directory and sort them in ascending order of modification date, one approach is to leverage the File.listFiles() method. However, this method doesn't guarantee the ordering of returned files.
A more refined solution involves customizing the sorting behavior using a Comparator. An anonymous Comparator can be created that compares files based on their modified timestamps:
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 code retrieves the file list via File.listFiles() and sorts it using the provided Comparator. This ensures that the oldest files, with the smallest modified timestamps, appear first in the sorted list.
The above is the detailed content of How Can I Get a Date-Sorted List of Files in Java?. For more information, please follow other related articles on the PHP Chinese website!