I created a list of files in a directory with f.listFiles().
Unfortunately they are very differently named like:
001.pdf
098.pdf
100.pdf
1000.pdf
now the array of files in the directory sets the 1000.pdf before the 100.pdf.
How can I sort this so that the files areback in the right order?
Thanks for help!
You may prepend the names with spaces to the same length:
File[] files = f.listFiles();
if(files != null) {
Arrays.sort(files, new Comparator<File>() {
@Override
public int compare(File o1, File o2) {
return String.format("%100s", o1.getName()).compareTo(
String.format("%100s", o2.getName()));
}
});
System.out.println(Arrays.toString(files));
}
Or shorter if you are using Java-8:
File[] files = f.listFiles();
if(files != null) {
Arrays.sort(files, Comparator.comparing(file -> String.format("%100s", file.getName())));
System.out.println(Arrays.toString(files));
}
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