#

Natural Order Filename Comparator

Kürzlich geschrieben und als nützlich empfunden:
Ein Comparator für Files, der eine natürliche Reihenfolge schafft, Nummernprefixe in Dateinamen ihrem Wert entsprechend sortiert, also z. B. "1.jpg", "2.jpg", "11.jpg", "a.jpg", was bei alphabetischer Sortierung (wie in den meisten Betreibssystemen eingesetzt) zu "1.jpg", "11.jpg", "2.jpg", "a.jpg" wird.

import java.io.File;
import java.text.Collator;
import java.util.Comparator;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
 
public class FilenameNaturalOrderComparator implements Comparator<File>{
  private static final Collator collator = Collator.getInstance();
  private static final Pattern pattern = Pattern.compile("^(\\d+)", Pattern.CASE_INSENSITIVE | Pattern.DOTALL);
 
  public int compare(File o1, File o2) {
    Matcher m = pattern.matcher(o1.getName());
    Long i1 = -1L;
    if (m.find()){
      i1 = Long.parseLong(m.group(1));
    }
    Long i2 = -1L;
    m = pattern.matcher(o2.getName());
    if (m.find()){
      i2 = Long.parseLong(m.group(1));
    }
 
    if (i1>=0 && i2>=0){
      return i1.compareTo(i2);
    }
    else if (i1>=0 && i2<0){
      return -1;
    }
    else if (i1<0 && i2>=0){
      return +1;
    }
    else{
      return collator.compare(o1.getName(), o2.getName());
    }
  }
}

Leave a Reply »»

Note: All comments are manually approved to avoid spam. So if your comment doesn't appear immediately, that's ok. Have patience, it can take some days until I have the time to approve my comments.