Search code examples
javajava-8nio

How to store Java nio files walk() result into a list of String?


I am working with Java 8 and I have the below code, which lists directory.

try (Stream<Path> paths = Files.walk(Paths.get("D:/MyDir"))) {
    paths.forEach(System.out::println);
} catch (IOException e) {
    e.printStackTrace();
}

I want to store the result to List<String> and need to suffix a \ if it's a directory. How can I do this?


Solution

  • What you ask isn't that hard :

        try (Stream<Path> paths = Files.walk(Paths.get("c:"))) {
            List<String> list = paths
                    .map(path -> Files.isDirectory(path) ? path.toString() + '/' : path.toString())
                    .collect(Collectors.toList());
        } catch (IOException e) {
            e.printStackTrace();
        }