繁体   English   中英

如何使用 java8 创建带有文件夹和相应文件的 Map

[英]How to create a Map with folder and corresponding file using java8

我想为路径创建一个 map。

该路径包含不同的文件夹,每个文件夹都有一些文件。

假设,路径:c:/project

该项目有 2 个文件夹 A 和 B。A 有 2 个文本文件 - 1.txt、2.txt 和 B 有 3.txt 文件 output 应该是 [A= {1.txt,2.txt}, B= {3 。文本}]

我正在使用 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();
    }

但是 output 是 {A=A,B=B}; 预期是 [A= {1.txt,2.txt}, B= {3.txt}]

试试这个:

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

, output

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

这里是 /Users/Fabien/project 的示例,它有 2 个文件夹 A 和 B。A 有 2 个文本文件 - 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);
    }

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM