2

嗨,我想根据数字对目录列表进行排序。我有名为11-20,1-5,6-10,21-30etc 的目录。现在我想根据其中的数字对它们进行排序,以便 1 到 N 个目录按顺序排列,我的意思是按顺序排列1-5,6-10,11-20,21-30。我正在使用以下代码,但它不起作用。

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

我是Java文件和目录操作的新手,请提前帮助谢谢。

4

2 回答 2

11

以下行:

Arrays.sort(dirList);

使用该File#compareTo()方法对文件进行排序,该方法基本上按路径名对文件进行排序。

您必须创建Comparator的自定义实现,然后调用:

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

例如 :

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);
于 2013-08-22T11:35:13.207 回答
1

除了 Arnauds 的回答,如果您只想拥有目录,还可以使用文件过滤器:

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

File[] dirList = mainDir.listFiles(filter);
于 2013-08-22T11:37:33.387 回答