Java 如何根据整数名称对目录进行排序?

Java 如何根据整数名称对目录进行排序?,java,Java,嗨,我想根据数字对目录列表进行排序。我有一些名为11-20,1-5,6-10,21-30等的目录。现在我想根据其中的数字对它们进行排序,以便1到N个目录按顺序排列,我的意思是按1-5,6-10,11-20,21-30的顺序排列。我正在使用以下代码,但它不起作用 File[] dirList = mainDir.listFiles(); Arrays.sort(dirList); 我不熟悉Java中的文件和目录操作,请提前帮助我,谢谢。下面一行: Arrays.sort(dirList); 使

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

File[] dirList = mainDir.listFiles();
Arrays.sort(dirList);
我不熟悉Java中的文件和目录操作,请提前帮助我,谢谢。

下面一行:

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

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

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);
比较器比较器=新比较器(){ @凌驾 公共整数比较(文件o1、文件o2){ /* *在这里,将两个文件与您自己的算法进行比较。 *下面是一个没有任何检查/异常捕获的示例 */ 字符串from1=o1.getName().split(“-”[0];//对于“1-5”,它将返回“1” 字符串from2=o2.getName().split(“-”[0];//对于“11-20”,它将返回“11” //转换为整数,然后比较: 返回Integer.parseInt(from2)-Integer.parseInt(from1); } } //然后使用比较器对文件进行排序: 排序(dirList,comparator);
除了Arnauds answer,如果您只想拥有目录,还可以使用文件过滤器:

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

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