Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get files in a directory sorted by last modified? [duplicate]

Tags:

java

java-7

In Java 7 with the new I/O APIs, is there an easy way to list a directory's content by last modified date? Basically I only need to get the file the wasn't modified for the longest time (sort by last modified ascending, take first filename).

like image 747
stefan.at.wpf Avatar asked Sep 03 '12 20:09

stefan.at.wpf


People also ask

How do I sort files by last modified?

Open File Explorer and navigate to the location where your files are stored. Sort files by Date Modified (Recent files first). Hold Shift key and click on the Name column. This will bring folders at the top with files sorted with Date Modified.

What command lists files sorted by last modified?

The 'ls' command lists all files and folders in a directory at the command line, but by default ls returns a list in alphabetical order. With a simple command flag, you can have ls sort by date instead, showing the most recently modified items at the top of the ls command results.

How do you sort files by date modified in Unix?

In order to ls by date or list Unix files in last modifed date order use the -t flag which is for 'time last modified'. or to ls by date in reverse date order use the -t flag as before but this time with the -r flag which is for 'reverse'.


1 Answers

There's no real "easy way" to do it, but it is possible:

List<Path> files = new ArrayList<>();
try(DirectoryStream<Path> stream = Files.newDirectoryStream(dir)) {
    for(Path p : stream) {
        files.add(p);
    }
}

Collections.sort(files, new Comparator<Path>() {
    public int compare(Path o1, Path o2) {
        try {
            return Files.getLastModifiedTime(o1).compareTo(Files.getLastModifiedTime(o2));
        } catch (IOException e) {
            // handle exception
        }
    }
});

This will sort the files soonest modified files last. DirectoryStreams do not iterate through subdirectories.

like image 71
Jeffrey Avatar answered Nov 05 '22 16:11

Jeffrey