我想为Path创建一个映射。
该路径包含不同的文件夹,每个文件夹都有一些文件。
比方说,路径:c:/project
该项目有两个文件夹A和B。A有两个文本文件——1.txt,2.txt,B有3.txt文件输出应该是[A={1.txt,2.txt},B={3.txt}]
我正在使用java8目前,我正在做
try (Stream<Path> files = Files.list(getOutputDirectory()))
{
Map<String, String> fileList = files.map(input -> input.toFile().getName())
.collect(Collectors.toMap(key -> key, value -> value));
logger.info("testing " + fileList);
}
catch (final IOException exception)
{
exception.printStackTrace();
}
但是输出是{A=A,B=B};应为[A={1.txt,2.txt},B={3.txt}]
我不知道你的完整代码是什么,但你可以试试这个:
Path getOutputDirectory = Paths.get("c:/project");
getOutputDirectory.toFile().getName();
try(Stream<Path> files = Files.list(getOutputDirectory)) {
Map<String, String<Path>> fileList =
files.collect(Collectors.groupingBy(p -> p.toFile().isDirectory()));
System.out.println(fileList);
} cath (IOException e) {
System.out.print(e.getMessage()); }
试试这个:
Map<String, List<String>> fileList = files.flatMap(path -> {
try {
return Files.list(path);
} catch (IOException e) {
e.printStackTrace();
}
return files;
}).collect(Collectors.groupingBy(path -> path.getParent().getFileName().toString(),
Collectors.mapping(path -> path.getFileName().toString(), Collectors.toList())));
,输出
{A=[1.txt, 2.txt], B=[3.txt]}
这里有一个/Users/Fabien/project的例子,它有两个文件夹A和B。A有两个文本文件-1.txt,2.txt和B有3.txt文件:
public static void main(String[] args) throws IOException {
Path projectPath = Paths.get("/Users/Fabien/project/");
Set<Path> directoriesToList = Files.list(projectPath).map(Path::getFileName).collect(Collectors.toSet());
Map<String, List<String>> fileList = Files.walk(projectPath).filter(p -> {
try {
return directoriesToList.contains(p.getParent().getFileName());
} catch (Exception e) {
return false;
}
}).collect(Collectors.groupingBy(p -> p.getParent().getFileName().toString()))
.entrySet().stream().collect(Collectors.toMap(Map.Entry::getKey, file -> file.getValue().stream().map(Path::getFileName).map(Path::toString).collect(Collectors.toList())));
System.out.println("testing " + fileList);
}