collections - Java 8 - 获取父目录和子目录列表的地图
问题描述
我有一个这样的文件夹结构:
/home/user/root/
dir1/
subDir1/
pdf1.pdf
log1.log
subDir2/
somefile.txt
subDir3
dir2/
subDir1
subDir4
subDir5
abc.txt
def.pdf
xyz.log
等等
我的要求是给定输入路径“/home/user/root/”,得到Map<String, List<String>>
如下:
key: dir1, value: [subDir1, subDir2, subDir3]
key: dir2, value: [subDir1, subDir4, subDir5]
...
...
也就是说,映射的键是给定输入下的第一级目录,然后每个键都有一个值,即第一级下的子目录列表。
我能够获得一级目录的列表:
private Set<String> listFilesUsingFileWalk(String rootDir, int depth) throws IOException {
Path path = Paths.get(rootDir);
try (Stream<Path> stream = Files.walk(path, depth)) {
return stream
.filter(file -> Files.isDirectory(file) && !file.equals(path))
.map(Path::getFileName)
//.forEach(d -> System.out.println(d.getFileName()));
.map(Path::toString)
.collect(Collectors.toSet());
}
}
但无法获得所需的输出。我认为递归可能是一种解决方案,但不能从 Java 8 流的角度来考虑。
请问这个可以建议吗?
解决方案
我仍然不确定您的深度参数的用途。但看起来你正在寻找这样的东西:
private Map<String,List<String>> listFilesUsingFileWalk(String rootDir, int depth) throws IOException {
Path path = Paths.get(rootDir);
try (Stream<Path> stream = Files.walk(path, depth)) {
return stream
.filter(file -> Files.isDirectory(file) && !file.equals(path))
.collect(Collectors.toMap(
(p) -> p.getFileName().toString(),
(p) -> Arrays.stream(p.toFile().listFiles()).filter(File::isDirectory).map(File::getName).collect(Collectors.toList())
));
}
}
或(不使用 File 类)
private Map<String,List<String>> listFilesUsingFileWalk(String rootDir, int depth) throws IOException {
Path path = Paths.get(rootDir);
try (Stream<Path> stream = Files.walk(path, depth)) {
return stream
.filter(file -> Files.isDirectory(file) && !file.equals(path))
.collect(Collectors.toMap(
(p) -> p.getFileName().toString(),
(p) -> {
try {
return Files.list(p).filter(Files::isDirectory).map(Path::getFileName).map(Path::toString).collect(Collectors.toList());
} catch (IOException e) {
return Collections.emptyList();
}
}
));
}
}
推荐阅读
- powershell - 使用 powershell 在 Web 中登录并下载文件
- python - 仅使用 python 生成 celery 工人而不会阻塞
- c# - 如何在 C# 中为 PropertyGrid 中的属性设置不同的文本对齐方式?
- javascript - 如何在 C# Selenium 中调用 Javascript 代码
- wordpress - 从编译的 dist 文件夹文件中链接用 JS 编写的 TinyMCE 插件 - IIFE 导致问题
- ios - 标签栏项目图标的大小非常奇怪
- node.js - 如何从令牌中获取用户 ID?
- regex - 如何在 Scala 中通过此 case 规则以仅接受包含字母的字符串?
- laravel - 在 Laravel 中,我试图从带有枢轴的表中获取信息
- list - 如何在 Prolog 列表中打包元组的元素