2

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!

bootsector
  • 49
  • 1
  • Are you using a list or an array? You're saying different things. – ManyQuestions Jul 08 '15 at 16:25
  • 1
    This question has been asked so many times before including [here](http://stackoverflow.com/questions/34518/natural-sorting-algorithm) – Codebender Jul 08 '15 at 16:25
  • thats true, I'm sorry. I'm using an array like File[] f = f.listFiles(); – bootsector Jul 08 '15 at 16:26
  • Create a comparator that compares the file names based on the integer value of the prefix of the file name. It will have to strip the extension (.pdf), and parse the result to an integer. – JB Nizet Jul 08 '15 at 16:27

2 Answers2

6

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));
}
Tagir Valeev
  • 97,161
  • 19
  • 222
  • 334
3

You can write a custom comparator if you have an array of strings

public class StringComparator implements Comparator<String> {
    @Override
    public int compare(String s1, String s2) {
       int n1 = Integer.parseInt(s1.substring(0, s1.indexOf(".") - 1));
       int n2 = Integer.parseInt(s2.substring(0, s2.indexOf(".") - 1));
       return n1 - n2;
    }
}
Shreevardhan
  • 12,233
  • 3
  • 36
  • 50