How to Iterate Through a Directory Tree in Java

The following example Java program iterates through all the files and directories in a given folder. It also walks through the entire directory tree printing names of sub-directories and files. Note that this example requires Java 8 or above since it uses java.nio.file.Files class and the walk method in it. The following program has 3 methods,

  • walkDirTree – Walks through the directory tree and print names of directories/files.
  • walkDirTreeWithSymLinks – Demonstrates the use of FileVisitOption for following symbolic links.
  • walkDirTreeAndSearch – Walks through the directory and prints file/directory names matching the search criteria. This method can be used for recursive file search.

Java 8 Files.walk Example Program

import java.nio.file.FileVisitOption;
import java.nio.file.Files;
import java.nio.file.Paths;

// Java sample program to iterate through directory tree
// Uses the Files.walk method added in Java 8
public class WalkDirectoryTree {
    public static void main(String[] args) throws Exception {
        // in windows use the form c:\\folder
        String rootFolder = "/Users/jj/temp";
        walkDirTree(rootFolder);
        walkDirTreeWithSymLinks(rootFolder);

        String searchFor = "png";
        walkDirTreeAndSearch(rootFolder, searchFor);

    }

    // Prints all file/directory names in the entire directory tree!
    private static void walkDirTree(String rootFolder) throws Exception {
        Files.walk(Paths.get(rootFolder)).forEach(path -> {
            System.out.println(path);
        });
    }

    // This example uses FileVisitOption to follow symbolic links
    // Prints all file/directory names in the entire directory tree
    // Prints all file/directory names in the entire directory tree!
    private static void walkDirTreeWithSymLinks(String rootFolder) throws Exception {
        Files.walk(Paths.get(rootFolder), FileVisitOption.FOLLOW_LINKS).forEach(path -> {
            System.out.println(path);
        });
    }

    // Walk the directory tree looking for files/folder with the search field
    // May throw AccessDeniedException or FileSystemLoopException exception.
    private static void walkDirTreeAndSearch(String rootFolder, String search) throws Exception {
        Files.walk(Paths.get(rootFolder), FileVisitOption.FOLLOW_LINKS).filter(t -> {
            return t.toString().contains(search);
        }).forEach(path -> {
            System.out.println(path);
        });
    }
}

One problem with walk method is that it can potentially throw AccessDeniedException or FileSystemLookException. In such cases, the above program will fail and there is no way to prevent it. One solution is to use the walkFileTree method in such cases. The following sample Java program illustrates the use of walkFileTree. As you can see it is much more verbose than walk example.

Java 8 walkFileTree Example Program

import java.io.IOException;
import java.nio.file.FileVisitResult;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.SimpleFileVisitor;
import java.nio.file.attribute.BasicFileAttributes;

//Java sample program to iterate through directory tree
// Uses the walkFileTree method
public class WalkFileTreeDemo {
    public static void main(String[] args) throws Exception{
        // in windows use the form c:\\folder
        String rootFolder = "/Users/jj";
        String searchFor = "png";
        walkFileTreeAndSearch(rootFolder,searchFor);
    }

    private static void walkFileTreeAndSearch(String rootFolder,String search) throws Exception {
        Files.walkFileTree(Paths.get(rootFolder), new MyFileVisitor(search));
    }
}

// There are multiple methods to override in SimpleFileVisitor
// We override only the visitFile method.
class MyFileVisitor extends SimpleFileVisitor<Path> {
    private String search;
    public MyFileVisitor(String s) {
        search = s;
    }
    @Override
    public FileVisitResult visitFile(Path file, BasicFileAttributes attrs) throws IOException {
        if(file.toString().contains(search)) {
            System.out.println(file.toString());
        }
        return FileVisitResult.CONTINUE;
    }
}

In addition to the visitFile, the following methods can be overridden from SimpleFileVisitor,

  • preVisitDirectory – Called before contents of a directory is visited
  • postVisitDirectory – Called after contents of a directory is visited
  • visitFileFailed – Called when there is an error such as FileSystemLoopException

The above methods can return one of the following FileVisitResult values,

  • CONTINUE – Continue file tree walk
  • TERMINATE – Terminate file tree walk
  • SKIP_SUBTREE – Continue without visiting the entries in this directory. This result is only meaningful when returned from the preVisitDirectory method; otherwise this result type is the same as returning CONTINUE.
  • SKIP_SIBLINGS – Continue without visiting the siblings of this file or directory. If returned from the preVisitDirectory method then the entries in the directory are also skipped and the postVisitDirectory method is not invoked

Also note that the walkFileTree is faster than the walk method.

Do you have a programming problem that you are unable to solve? Please send us your problem and we will publish the solution! Please email us.

Leave a Reply