Home > Java > javaTutorial > How to Sort Files in a Java Directory by Modification Date (Oldest First)?

How to Sort Files in a Java Directory by Modification Date (Oldest First)?

Barbara Streisand
Release: 2024-11-28 18:16:14
Original
483 people have browsed it

How to Sort Files in a Java Directory by Modification Date (Oldest First)?

Sorting Files by Date Modified in Java

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());
    }
});
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template