Java Files.walk examples

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

  1. Java docs – Files.walk

About the Author

author image
mkyong
Founder of Mkyong.com, love Java and open source stuff. Follow him on Twitter. If you like my tutorials, consider make a donation to these charities.

Comments

avatar