How to use Files.walk()… to get a graph of files based on conditions?

前端 未结 3 1767
名媛妹妹
名媛妹妹 2021-02-01 04:24

I have the following directory structures:

/path/to/stuff/org/foo/bar/
/path/to/stuff/org/foo/bar/1.2.3/
/path/to/stuff/org/foo/bar/1.2.3/myfile.ext
/path/to/stu         


        
3条回答
  •  伪装坚强ぢ
    2021-02-01 05:05

    Adding to @a-better-oliver's answer, here is what you can do if your action declares IOExceptions.

    You can treat the filtered stream as an Iterable, and then do your action in a regular for-each loop. This way, you don't have to handle exceptions inside a lambda.

    try (Stream pathStream = Files
            .walk(Paths.get("/path/to/stuff/"))
            .filter(p -> p.toString().endsWith(".ext"))
            .map(p -> p.getParent().getParent())
            .distinct()) {
    
        for (Path file : (Iterable) pathStream::iterator) {
            // something that throws IOException
            Files.copy(file, System.out);
        }
    }
    

    Found that trick here: https://stackoverflow.com/a/32668807/1207791

提交回复
热议问题