如何对列表<文件>进行排序首先列出目录并按目录分组文件? [英] How to sort List&lt;File&gt; to list directories first and grouping files by directory?

查看:16
本文介绍了如何对列表<文件>进行排序首先列出目录并按目录分组文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

为了获取指定目录中包含的所有文件并根据某些扩展名,我使用了方法 listFilesFileUtils 来自 Apache Commons IO 库,如以下代码示例所示.

In order to get all files contained in a specified directory and according to some extensions, I'm using the method listFiles of class FileUtils from Apache Commons IO library, as in the following code sample.

ArrayList<String> wildcards = new ArrayList<>();
wildcards.add("*.cpp");
wildcards.add("*.h");
wildcards.add("*.txt");

File dir = new File("/path/to/dir");
Collection<File> found = FileUtils.listFiles(
        dir,
        new WildcardFileFilter(wildcards, IOCase.SENSITIVE),
        DirectoryFileFilter.DIRECTORY);

List<File> files = new ArrayList<>(found);

结果 Collection 中项目的顺序在不同的操作系统中有所不同,所以我将它们(即包装列表 files)按照遵循以下规则.

The order of items in the resulting Collection<File> varies in the different operating systems, so I would sort them (ie. the wrapping list files) in according to the following rules.

  • 目录应列在文件之前.
  • 排序例程应按目录对文件进行分组.

示例:

/path/to/dir/first/subpath/main.cpp
/path/to/dir/first/subpath/utils.cpp
/path/to/dir/first/subpath/utils.h
/path/to/dir/first/main.cpp
/path/to/dir/first/utils.cpp
/path/to/dir/first/utils.h
/path/to/dir/second/main.cpp
/path/to/dir/second/utils.cpp
/path/to/dir/second/utils.h
/path/to/dir/README.txt

推荐答案

您可以使用 Java 8 的 stream 来解决您的问题.这样的事情应该可以工作:

You can use Java 8's streams to solve your problem. Something like this should work:

//untested
Map<Path, List<Path>> dirToFileMap = files.stream()
            .map(f -> Paths.get(f.getAbsolutePath()))
            .collect(Collectors.groupingBy(Path::getParent));

使用该地图,您可以实现所需.例如,首先迭代 keySet.

With that map you can achieve what you need. Iterate over keySet first, for example.

这篇关于如何对列表<文件>进行排序首先列出目录并按目录分组文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆