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();
}
}
));
}
}

因为您的目录名是唯一的,所以您可以采用这种方法。也不需要递归.

Map<String, List<String>> collect = stream
.filter(file -> Files.isDirectory(file) && !file.equals(path))
.filter(file -> !file.getParent().equals(path))
.collect(Collectors.groupingBy(p -> p.getParent().getFileName().toString(), Collectors.mapping(p -> p.getFileName().toString(), Collectors.toList())));

注意:这会给你所有的父/子目录。

private Map<String, List<String>> listFilesUsingFileWalk(String rootDir, int depth) throws IOException {
Path path = Paths.get(rootDir);
Stream<Path> stream = Files.walk(path, depth);
return stream
.filter(file -> Files.isDirectory(file) && !file.equals(path))
.filter(file -> !file.getParent().equals(path))
.collect(Collectors.groupingBy(p -> p.getParent().getFileName().toString(), Collectors.mapping(p -> p.getFileName().toString(), Collectors.toList())));
}

最新更新