Best way to list files in Java, sorted by Date Modified?
I think your solution is the only sensible way. The only way to get the list of files is to use File.listFiles() and the documentation states that this makes no guarantees about the order of the files returned. Therefore you need to write a Comparator that uses File.lastModified() and pass this, along with the array of files, to Arrays.sort().
Get files in a directory sorted by last modified?
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.
How to sort files from a directory by date in java?
Java 8
public static void sortOldestFilesFirst(File[] files) {
Arrays.sort(files, Comparator.comparingLong(File::lastModified));
}
public static void sortNewestFilesFirst(File[] files) {
Arrays.sort(files, Comparator.comparingLong(File::lastModified).reversed());
}
Java 7
public static void sortOldestFilesFirst(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File a, File b) {
return Long.compare(a.lastModified(), b.lastModified());
}
});
}
public static void sortNewestFilesFirst(File[] files) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File a, File b) {
return Long.compare(b.lastModified(), a.lastModified());
}
});
}
How do I sort results of File.listFiles() by creation date?
you can use Collections.sort or Arrays.sort or List.sort
You can get the creation date of a file by using java nio Files. readAttributes()
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(final File o1, final File o2) {
try {
BasicFileAttributes f1Attr = Files.readAttributes(Paths.get(f1.toURI()), BasicFileAttributes.class);
BasicFileAttributes f2Attr = Files.readAttributes(Paths.get(f2.toURI()), BasicFileAttributes.class);
return f1Attr.creationTime().compareTo(f2Attr.creationTime());
} catch (IOException e) {
return 0;
}
}
});
Or using Comparator.comparing:
Comparator<File> comparator = Comparator.comparing(file -> {
try {
return Files.readAttributes(Paths.get(file.toURI()), BasicFileAttributes.class).creationTime();
} catch (IOException e) {
return null;
}
});
Arrays.sort(files, comparator);
display files from a directory with their time stamps [last modified date] so that to move least used files to a temporary folder
for (int i = 0; i < listOfFiles.length; i++)
{
System.out.println(listOfFiles[i].getName()+"\t"+new Date(listOfFiles[i].lastModified()));
}
java : Sort Files based on Creation Date
Try flipping the comparison order:
return new Long(((File)o2).lastModified()).compareTo(new Long(((File) o1).lastModified()));
This works for me testing locally just now.
how to sort files during processing in Java
You want to sort those Files by date. The method Files.walk()
will return Stream<Path>
and it will be sorted by the name and not the date, it doesn't even have the date as the values are paths.
You can use the .sorted()
method with a comparator to sort after last modified:
Files.walk(indir, 1, FileVisitOption.FOLLOW_LINKS)
.sorted(Comparator.comparingLong(p -> p.toFile().lastModified()))
.forEachOrdered(System.out::println);
This uses the Comparator class to compare the long value returned by .lastModified()
.
https://docs.oracle.com/javase/8/docs/api/java/util/Comparator.html
https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#sorted--
how to File.listFiles in alphabetical order?
The listFiles
method, with or without a filter does not guarantee any order.
It does, however, return an array, which you can sort with Arrays.sort()
.
File[] files = XMLDirectory.listFiles(filter_xml_files);
Arrays.sort(files);
for(File _xml_file : files) {
...
}
This works because File
is a comparable class, which by default sorts pathnames lexicographically. If you want to sort them differently, you can define your own comparator.
If you prefer using Streams:
A more modern approach is the following. To print the names of all files in a given directory, in alphabetical order, do:
Files.list(Paths.get(dirName)).sorted().forEach(System.out::println)
Replace the System.out::println
with whatever you want to do with the file names. If you want only filenames that end with "xml"
just do:
Files.list(Paths.get(dirName))
.filter(s -> s.toString().endsWith(".xml"))
.sorted()
.forEach(System.out::println)
Again, replace the printing with whichever processing operation you would like.
Related Topics
Comparator.Reversed() Does Not Compile Using Lambda
Powermockito Mock Single Static Method and Return Object
Integer Wrapper Objects Share the Same Instances Only Within the Value 127
How to Set a Background Picture in JPAnel
Use Mockito to Mock Some Methods But Not Others
Why Jsf Saves the State of UI Components on Server
When Should a Class Be Comparable And/Or Comparator
Best Way to List Files in Java, Sorted by Date Modified
Why Can't Strings Be Mutable in Java and .Net
Difference Between String Replace() and Replaceall()
In What Order Do Static/Instance Initializer Blocks in Java Run