2013-08-22 43 views
2

嗨我想根据数字排序目录列表​​。我有像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操作请帮助提前感谢。

回答

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); 
1

除了Arnauds答案,如果你只是想有目录,你可以使用文件过滤器另外:

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

File[] dirList = mainDir.listFiles(filter); 
相关问题