Java Files.walk examples
Java File.walk method is available in Java 8. It is very useful to traverse the content of a file tree. Walk goes in a depth-first fashion and returns a Stream object. We can then work with the stream to get the required result, like filtering only directories, finding files matching some name, etc. This article covers three examples of using File.walk to list all directories, files, and both.
List all the folders
List all the directories/folders inside the location specified by path.
public List getFolders(String path) throws IOException {
try (Stream walk = Files.walk(Paths.get(path))) {
List result = walk.filter(Files::isDirectory)
.map(x -> x.getFileName().toString())
.collect(Collectors.toList());
result.forEach(System.out::println);
return result;
}
}
List all files
Similar to the above method, but here we filter only regular files with Files::isRegularFile.
public List getFiles(String path) throws IOException {
try (Stream walk = Files.walk(Paths.get(path))) {
List result = walk.filter(Files::isRegularFile)
.map(x -> x.getFileName().toString())
.collect(Collectors.toList());
result.forEach(System.out::println);
return result;
}
}
Files and Directories
This method will list all directories along with files inside them. It is similar to the Linux command `ls *`.
public List getFoldersAndFiles(String path) throws IOException {
try (Stream walk = Files.walk(Paths.get(path))) {
List result = walk.map(x -> {
if (Files.isDirectory(x)) {
return x.getFileName().toString() + ":";
} else {
return x.getFileName().toString();
}
}).collect(Collectors.toList());
result.forEach(System.out::println);
return result;
}
}