简体   繁体   English

排序文件列表

[英]Sort a List of File

How can I list the files of multiple directorys in Java? 如何在Java中列出多个目录的文件?

That's what I've tried: 那就是我尝试过的:

ArrayList<File> files = new ArrayList<File>();
for(int x = 0; x < directorys.length; x++) {
    if(directorys[x].isDirectory()) {
        files.addAll(Arrays.asList(directorys[x].listFiles(filter)));
    } 
}

That works kind of, but the problem is, that it doesn't bring the files into a fully alphabetic order. 这种方法有点奏效,但问题是它不会使文件完全按字母顺序排列。
It's than sth. 比什么都重要。 like this: (first folder) 1, 3, 5, (second folder) 2, 4, 6 . 像这样:( 第一个文件夹)1、3、5(第二个文件夹)2、4、6 But I'd like it to be like this: 1, 2, 3, 4, 5, 6 . 但我希望这样: 1,2,3,4,5,6
So I guess, what it does, is that it brings all the files of each folder into the correct order, but not all files together. 所以我想,它的作用是将每个文件夹的所有文件按正确的顺序排列,而不是将所有文件合并在一起。
How could I achieve that? 我该如何实现?

您可以使用比较器进行排序:

files.sort((a,b)-> a.getName().compareTo(b.getName()));

您可以在循环后对文件列表进行排序,如下所示

files.sort(Comparator.comparing(File::getName));

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM