Java Zero to All All questionsPractise free
Interview questions › Java Foundations — Zero to Basics › File I/O — java.io, NIO2 & Files API

How do you walk a directory tree safely, and what are the pitfalls of Files.walk versus Files.walkFileTree?

Level III · MidFile I/O — java.io, NIO2 & Files API
Short answer

Files.walk returns a lazy Stream<Path> and is concise, but it holds open directory handles (use try-with-resources), can throw partway through on an unreadable entry, and by default does not follow symlinks (FOLLOW_LINKS risks infinite cycles).

Explanation

Files.walkFileTree with a FileVisitor is more verbose but gives fine-grained control: you can handle visit failures per-file, prune subtrees with SKIP_SUBTREE, and post-visit directories — which is exactly what you need to implement a correct recursive delete (delete children before the directory).

Common mistakes
  • Not closing the Stream from Files.walk.
  • Following symbolic links into cycles.

Can you say this out loud in two minutes? Drill it in a timed mock interview, with flashcards and runnable code for File I/O — java.io, NIO2 & Files API.

Practise free

More on File I/O — java.io, NIO2 & Files API