how to File.listFiles in alphabetical order?
In Java 8:
Arrays.sort(files, (a, b) -> a.getName().compareTo(b.getName()));
Reverse order:
Arrays.sort(files, (a, b) -> -a.getName().compareTo(b.getName()));
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.