This code tip shows how to use Java NIO API to recursively list all sub-directories and files in a given directory.
The directory structure iterated in the below example is –
C:\JavaBrahman\Level1 which has the structure, shown using the DOS command –
DIR /s /b –
- To read through, or walk, through a file tree of a system,
NIOlibraries have provided the
Files.walkFileTree()static method. The most basic version of this method takes 2 inputs – a starting
- The starting
Pathhas to be an instance of
java.nio.file.FileVisitoris also an interface whose most commonly used implementation has been provided by the JDK and is known as
SimpleFileVisitor. An implementation of
SimpleFileVisitoras an anonymous inner class has been created which overrides two methods –
visitFile(). The anonymous inner class implementation is named –
simpleFileVisitor(note the camel casing for object names).
- As the
NIO APIwalks the file tree, these two methods are the hooks which let us process events. While
preVisitDirectory()method is invoked when a directory is to be visited next, and
visitFile()method is invoked when a file is actually visited.
NIO APIuses visitor patternClick to read detailed tutorial on Visitor Design Pattern to walk through the files.
DIRECTORY LOCATIONis printed for each directory visited while the
FILE NAMEis printed for each visited file.
- To invoke the
Files.walkFileTree()method, first an instance of
FileSystemis obtained from
FileSystemsis a factoryClick to read detailed tutorial on Factory Design Pattern of file systems and the
getDefault()method returns a handle to the default file system on which the system is running.
- Then from the
fileSysteminstance we create the a
rootPath, with the path
- Lastly, we invoke the
Files.walkFileTree()method with the
rootPathobject and the