Umesh Kacha
Umesh Kacha

Reputation: 13666

How to sort directories based on name which is integer?

I would like to sort list of directories based on numbers. I have directories named like 11-20,1-5,6-10,21-30 etc. Now I want to sort them based on numbers in it so that 1 to N directories come in order I mean in order 1-5,6-10,11-20,21-30. I am using the following code but it's not working.

File[] dirList = mainDir.listFiles();
Arrays.sort(dirList);

I am new to file and directory manipulation in Java. What can I try next?

Upvotes: 2

Views: 128

Answers (2)

Arnaud Denoyelle
Arnaud Denoyelle

Reputation: 31225

The following line :

Arrays.sort(dirList);

sorts your files using the File#compareTo() method, which basically sorts your files by pathname.

You must create a custom implementation of Comparator then call :

Arrays.sort(dirList, new YourCustomComparator());

For example :

Comparator<File> comparator = new Comparator<File>() {
  @Override
  public int compare(File o1, File o2) {
    /*
     * Here, compare your two files with your own algorithm.
     * Here is an example without any check/exception catch
     */
    String from1 = o1.getName().split("-")[0]; //For '1-5', it will return '1' 
    String from2 = o2.getName().split("-")[0]; //For '11-20', it will return '11'

    //Convert to Integer then compare : 
    return Integer.parseInt(from2)-Integer.parseInt(from1);
  }
}

//Then use your comparator to sort the files:
Arrays.sort(dirList, comparator);

Upvotes: 11

mnkypete
mnkypete

Reputation: 329

In addition to Arnauds answer, if you only want to have directories, you can use a file filter in addition:

FileFilter filter = new FileFilter()
{
   public boolean accept(File file) {
     return file.isDirectory();
   }
};

File[] dirList = mainDir.listFiles(filter);

Upvotes: 1

Related Questions