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).
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.
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.
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'.
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. DirectoryStream
s do not iterate through subdirectories.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With