按文件名对文件路径数组排序

我用来directory.listFiles()从给定的目录结构中递归地获取文件列表。为此,我尝试使用以下代码,但它们都不起作用。

    Arrays.sort(fList, Comparator.comparing(File::getName));
    Arrays.sort(fList, NameFileComparator.NAME_COMPARATOR);

文件应从所有子目录中按升序排列。


繁星coding
浏览 170回答 3
3回答

沧海一幻觉

File 是一个可比较的类,默认情况下按字典顺序对路径名进行排序。只需使用, Arrays.sort(fList);如果你想对它们进行不同的排序,你可以定义你自己的比较器。

MMTTMM

如果你想在树结构中递归地对所有文件路径进行排序,你可以尝试Files.walk使用sortedJava 8 流:List<String> files = Files.walk(Paths.get("/tmp"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(Files::isRegularFile) // Check you have only file names&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(Path::toString) // map to string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.sorted() // sort&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList()); // create list如果你想要不区分大小写的排序:List<String> files = Files.walk(Paths.get("d:/tmp"))&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.filter(Files::isRegularFile) // Check you have only file names&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.map(Path::toString) // map to string&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.sorted(Comparator.comparing(String::toLowerCase)) // sort case insensitive&nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp; &nbsp;.collect(Collectors.toList()); // create list

冉冉说

要列出目录和子目录中的所有文件,请使用Apache Commons FilesUtil.listFiles方法Collection<File> fCollection = FileUtils.listFiles(directory, null, true);File[] fList = fCollection.toArray(new File[fCollection.size()]);然后对数组进行排序,您可以使用Arrays.sort(fList);
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Java