Several Useful Things In One Sorting Function

So if you want to get all the files in a directory that have a certain extension and sort them by a number that is present in their name (because the normal "comparTo" annoyingly does not do this when you have two digit numbers even if the file names are the same and the numbers are in the same place in each one) you can do this:

public File[] getTSPFileArray(File dir){
if(dir == null)
dir = new File("/home/x/Desktop/school/ar_int/data_ts");

File[] files = dir.listFiles();

// This filter only returns files.
FileFilter fileFilter = new FileFilter()

public boolean accept(File file)
return !file.isDirectory() && file.getName().endsWith(".tsp");
files = dir.listFiles(fileFilter);

// Sort files by name.
Arrays.sort(files, new Comparator()

public int compare(Object arg0, Object arg1) {
Pattern p = Pattern.compile ("[\\d]+");
Matcher m1 = p.matcher(((File) arg0).getName());
Matcher m2 = p.matcher(((File) arg1).getName());
if(m1.find() && m2.find()){
System.out.println(m1.group() + " compare with "+m2.group());
return Integer.parseInt(m1.group()) - Integer.parseInt(m2.group());
} else {
return 0;


return files;

Did you like the climactic part where I pulled the numbers out with a regex pattern matcher?

No comments: