Home > Java > javaTutorial > body text

How Can I Get a Date-Sorted List of Files in Java?

Patricia Arquette
Release: 2024-11-28 02:57:09
Original
236 people have browsed it

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

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!

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