Как создать карту с папкой и соответствующим файлом с помощью java8 - PullRequest
0 голосов
/ 10 июля 2020

Я хочу создать карту для пути.

Этот путь содержит разные папки, и в каждой папке есть несколько файлов.

Скажем, путь: c: / project

В проекте есть 2 папки A и B. A имеет 2 текстовых файла - 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}]

Ответы [ 3 ]

1 голос
/ 10 июля 2020

Я не знаю, каков ваш полный код, но вы можете попробовать это:

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()); }
1 голос
/ 10 июля 2020

Попробуйте это:

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]}
0 голосов
/ 10 июля 2020

Вот пример с / 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);
    }
...