Java Files.walk examples
By:Roy.LiuLast updated:2019-08-11
The Files.walk API is available in Java 8, it is recommended to use try-with-resources to close the Files.walk stream.
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { //...
1. List all files.
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isRegularFile) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();
2. List all folders.
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.filter(Files::isDirectory) .map(x -> x.toString()).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();
3. List all files end with .txt
try (Stream<Path> walk = Files.walk(Paths.get("C:\\projects"))) { List<String> result = walk.map(x -> x.toString()) .filter(f -> f.endsWith(".txt")).collect(Collectors.toList()); result.forEach(System.out::println); } catch (IOException e) { e.printStackTrace();
References
From:一号门
Previous:Java ProcessBuilder examples
COMMENTS