I want to list all the files on my computer recursively using Java 8.
Java 8 provides a listFiles
method that returns all the files and directories but without recursion. How can I use it to get a full recursive list of files (without using a mutating collection)?
I've tried the code below but it only goes one level deep:
static Function<Path, Stream<Path>> listFiles = p -> {
if (p.toFile().isDirectory()) {
try { return Files.list(p); }
catch (Exception e) { return Stream.empty(); }
} else {
return Stream.of(p);
}
};
public static void main(String[] args) throws IOException {
Path root = Paths.get("C:/temp/");
Files.list(root).flatMap(listFiles).forEach(System.out::println);
}
And using return Files.list(p).flatMap(listFiles);
does not compile (not sure why)...
Note: I am not interested in solutions involving FileVisitors or external libraries.
Files.walkFileTree
? Or, do you really really just want to use a recursive stream? :-) – PrerecordFiles.walk
. It takes a Path and returns a Stream<Path>. – Prerecord