We have a situation where our directory has files with a prefix (say MyFile
), followed by a number (e.g. MyFile1, MyFile2, MyFile3, …). We would like to return the list of filenames in the directory, but in numeric order. For example MyFile1, MyFile2, MyFile3, … , MyFile9, MyFile10, MyFile11, MyFile12 etc.).
The Java File
class list()
method returns the list of filenames but in lexicographic order (MyFile1, MyFile10, MyFile11, MyFile12, MyFile2, MyFile3…. , MyFile9 etc.). Is there an API call that would return the filenames in the order we want?
Addendum
A slight variant of the solution suggested in Java File.list() consistent order? has worked for me. I have created a new method called generateConsistentOrder
. The code is as follows:
protected void generateConsistentOrder(String[] files, String prefixToDrop) {
Arrays.sort(
files,
new Comparator<String>() {
public int compare(String a, String b) {
Integer retVal = null;
try {
Integer intA = Integer.parseInt(a.substring(a.indexOf(prefixToDrop)+prefixToDrop.length()));
Integer intB = Integer.parseInt(b.substring(b.indexOf(prefixToDrop)+prefixToDrop.length()));
retVal = intA.compareTo(intB);
}
catch (Exception e) {
retVal = a.compareTo(b);
}
return retVal;
}
});
}