嗨,我想根据数字排序目录列表.我有目录名称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);
Run Code Online (Sandbox Code Playgroud)
我是Java新文件和目录操作请提前帮助感谢.
Arn*_*lle 11
以下行:
Arrays.sort(dirList);
Run Code Online (Sandbox Code Playgroud)
使用该File#compareTo()方法对文件进行排序,该方法基本上按路径名对文件进行排序.
您必须创建Comparator的自定义实现,然后调用:
Arrays.sort(dirList, new YourCustomComparator());
Run Code Online (Sandbox Code Playgroud)
例如 :
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);
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
105 次 |
| 最近记录: |