Walking file tree using walk method of Files class.

1. Overview

In this article we will look at Files class’s walk method. walk() method returns the content of directory passed in parameter. The contents are returned lazily in Stream object that contains Path to all the contents in directory.

The listing returned in Stream is recursive and traversed in depth first search traversal manner. Which means that the listing provided will navigate directory/directories.

There are two flavors of walk() method. One method doesn’t accept the maxDepth parameter, which signifies the maximum depth of directories to search for and other method accepts maxDepth parameter.

2. walk(Path start, FileVisitOption… options) method

walk() method accepts java.nio.file.Path as parameter and FileVisitOptions. In this method the maxDepth value is defaulted to Integer.MAX_VALUE

The below example pulls in the files and folder from directory.

String path1 = getClass().getResource("/Text-Files")
                         .toURI().getPath();
 
Files
	.walk(Paths.get(path1))
	.filter(Files::isRegularFile)
	.collect(Collectors.toList())
	.forEach(System.out::println);
 
 
Output:
/Text-Files/File2.txt
/Text-Files/File3.txt
/Text-Files/File1.txt
/Text-Files/Mark-Twain/Story1.txt
/Text-Files/Mark-Twain/Story2.txt
/Text-Files/Mark-Twain/Story3.txt
/Text-Files/Dan-Brown/Novel1.txt
/Text-Files/Dan-Brown/Novel2.txt
/Text-Files/Dan-Brown/Novel3.txt

3. walk(
Path start, int maxDepth, FileVisitOption… options) method

maxDepth parameter signifies the recursion level or depth first search level from starting directory.

int maxDepth = 1;
 
String path1 = getClass().getResource("/Text-Files")
                         .toURI().getPath();
 
Files
	.walk(Paths.get(path1), maxDepth)
	.filter(Files::isRegularFile)
	.collect(Collectors.toList())
	.forEach(System.out::println);
 
Output:
/Text-Files/File2.txt
/Text-Files/File3.txt
/Text-Files/File1.txt

4. Print text files from directory

String path = getClass().getResource("/Text-Files")
                        .toURI().getPath();
 
Files
	.walk(Paths.get(path))
	.filter(Files::isRegularFile)
	.filter(predicate("txt"))
	.flatMap(path -> uncheckedReading(path).stream())
	.forEach(System.out::println);
 
Predicate<Path> predicate(String extension) {
	return path -> path.getFileName()
					.toString().endsWith(extension);
}
 
private List<String> uncheckedReading(Path path) {
	try {
		return Files.readAllLines(path);
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}

5. Collect text in List from directory

String path = getClass().getResource("/Text-Files")
                        .toURI().getPath();
 
Files
	.walk(Paths.get(path))
	.filter(Files::isRegularFile)
	.filter(predicate("txt"))
	.flatMap(path -> uncheckedReading(path).stream())
	.collect(Collectors.toList());
 
Predicate<Path> predicate(String extension) {
	return path -> path.getFileName()
					.toString().endsWith(extension);
}
 
private List<String> uncheckedReading(Path path) {
	try {
		return Files.readAllLines(path);
	} catch (IOException e) {
		throw new UncheckedIOException(e);
	}
}

6. Conclusion

In this article, we saw how to use walk method to read all the content from the directory. Feel free to play around using different examples. walk() is a powerful method as it allows us to use all the methods of Stream interface.

Leave a Reply

Your email address will not be published. Required fields are marked *