1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87
| import java.io.File;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
public class FileNameWithNumberComparator
implements Comparator<File> {
public int compare(File file1, File file2) {
String fileName1 = file1.getName();
String fileName2 = file2.getName();
int i1 = 0;
int i2 = 0;
Character c1, c2;
String sub1, sub2;
while (i1 < fileName1.length() && i2 < fileName2.length()) {
c1 = fileName1.charAt(i1);
c2 = fileName2.charAt(i2);
if (Character.isDigit(c1) && Character.isDigit(c2)) {
sub1 = readNumber(fileName1, i1);
sub2 = readNumber(fileName2, i2);
int c = Integer.parseInt(sub1) - Integer.parseInt(sub2);
if (c != 0)
return c;
if (!sub1.equals(sub2)) {
return sub1.compareTo(sub2);
}
i1 += sub1.length();
i2 += sub2.length();
} else {
int c = c1.compareTo(c2);
// Si File001.xml == file001.xml, décommenter la ligne suivante
// et commenter la précédente
// int c = c1.toUpperCase().compareTo(c2.toUpperCase());
if (c != 0)
return c;
i1++;
i2++;
}
}
return (fileName1.length() - i1) - (fileName2.length() - i2);
}
private static String readNumber(String fileName, int offset) {
for (int i = offset + 1; i < fileName.length(); i++) {
if (!Character.isDigit(fileName.charAt(i))) {
return fileName.substring(offset, i);
}
}
return fileName.substring(offset);
}
public static void main(String... args) {
HashSet<File> files = new HashSet<File>();
for (int i = 1; i < 50; i++) {
files.add(new File(i + ".xml"));
}
for (int i = 1; i < 50; i++) {
files.add(new File("toto"+(i < 10 ? "0" : "") + i+".xml"));
}
for (int i = 1; i < 50; i++) {
files.add(new File("tata"+i+".xml"));
}
for (int i = 1; i < 50; i++) {
files.add(new File("toto0"+(i < 10 ? "0" : "") + i+".xml"));
}
ArrayList<File> orderedFiles = new ArrayList<File>(files);
System.out.println("unordered files:");
for (File fileName : orderedFiles) {
System.out.println(fileName.getName());
}
Collections.sort(orderedFiles, new FileNameWithNumberComparator());
System.out.println("Ordered files:");
for (File fileName : orderedFiles) {
System.out.println(fileName.getName());
}
}
} |
Partager