JB Header
Java - How to recursively list all files and subdirectories in a directory with examples
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 -
C:\JavaBrahman\Level1>DIR /s /b
C:\JavaBrahman\Level1\file1.txt
C:\JavaBrahman\Level1\file2.txt
C:\JavaBrahman\Level1\Level2
C:\JavaBrahman\Level1\Level2\file3.txt
C:\JavaBrahman\Level1\Level2\file4.txt
Java code to recursively iterate over a directory
package com.javabrahman.corejava;
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.FileVisitor;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.FileVisitResult;
import java.nio.file.FileSystems;
import java.nio.file.FileSystem;
import java.nio.file.Files;
import java.nio.file.attribute.BasicFileAttributes;
public class RecursiveFileVisitor {
  public static void main(String args[]) {
    
    FileVisitor<Path> simpleFileVisitor = new SimpleFileVisitor<Path>() {
      @Override
      public FileVisitResult preVisitDirectory(Path dir,BasicFileAttributes attrs)
          throws IOException {
        System.out.println("-------------------------------------");
        System.out.println("DIRECTORY NAME:"+ dir.getFileName() 
                           + "LOCATION:"+ dir.toFile().getPath());
        System.out.println("-------------------------------------");
        return FileVisitResult.CONTINUE;
      }
      
      @Override
      public FileVisitResult visitFile(Path visitedFile,BasicFileAttributes fileAttributes)
          throws IOException {
        System.out.println("FILE NAME: "+ visitedFile.getFileName());
        return FileVisitResult.CONTINUE;
      }
    };
    FileSystem fileSystem = FileSystems.getDefault();
    Path rootPath = fileSystem.getPath("C:\\JavaBrahman\\LEVEL1");
    try {
      Files.walkFileTree(rootPath, simpleFileVisitor);
    } catch (IOException ioe) {
      ioe.printStackTrace();
    }
  }
}
 OUTPUT of the above code
---------------------------------------
DIRECTORY NAME: LEVEL1    LOCATION: C:\JavaBrahman\LEVEL1
---------------------------------------
FILE NAME: file1.txt
FILE NAME: file2.txt
---------------------------------------
DIRECTORY NAME: Level2    LOCATION: C:\JavaBrahman\LEVEL1\Level2
---------------------------------------
FILE NAME: file3.txt
FILE NAME: file4.txt
Explanation of the code
  • To read through, or walk, through a file tree of a system, NIO libraries have provided the Files.walkFileTree() static method. The most basic version of this method takes 2 inputs - a starting Path and a FileVisitor.
  • The starting Path has to be an instance of java.nio.file.Path interface.
  • java.nio.file.FileVisitor is also an interface whose most commonly used implementation has been provided by the JDK and is known as SimpleFileVisitor. An implementation of SimpleFileVisitor as an anonymous inner class has been created which overrides two methods - preVisitDirectory() and visitFile(). The anonymous inner class implementation is named - simpleFileVisitor(note the camel casing for object names).
  • As the NIO API walks 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.
  • The NIO API uses visitor patternClick to read detailed tutorial on Visitor Design Pattern to walk through the files.
  • DIRECTORY NAME and DIRECTORY LOCATIONis printed for each directory visited while the FILE NAME is printed for each visited file.
  • To invoke the Files.walkFileTree() method, first an instance of FileSystem is obtained from FileSystems.getDefault() method. FileSystems is 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 fileSystem instance we create the a Path instance, named rootPath, with the path "C:\\JavaBrahman\\LEVEL1".
  • Lastly, we invoke the Files.walkFileTree() method with the rootPath object and the simpleFileVisitor object.