How to traverse a folder or directory recursively using Java File API

This example shows how we can traverse a folder or directory structure using recursive algorithm by writing a small java program using Java File API.

Technologies used in this article

  1. JDK 1.6
  2. Eclipse 3.7

1. Create a Java Project and a Class with 'main' method

Create a java project ('RecursiveFolderTraversar') and a class ('FolderTraversar') in eclipse to run the sample code to print directory structure of the folder / directory given as input.

Sample project structure is shown below

2. Write Code

Add a method called 'traverse(File parentNode, String leftIndent)' as shown below and call the same from your 'main' method.

File: FolderTraversar.java

package com.srccodes.example;
 
import java.io.File;
 
/**
 * @author srccodes.com
 * @version 1.0
 * 
 */
public class FolderTraversar {
 
    /**
     * @param args
     */
    public static void main(String[] args) {
        // Folder that you want to traverse
        File inputFolder = new File("c:/inputFolder");
        traverse(inputFolder, "");
    }
 
    public static void traverse(File parentNode, String leftIndent) {
        if (parentNode.isDirectory()) {
            System.out.println(leftIndent + parentNode.getName());
 
            // Use left padding to create tree structure in the console output.
            leftIndent += "   ";
 
            File childNodes[] = parentNode.listFiles();
            for (File childNode : childNodes) {
                traverse(childNode, leftIndent);
            }
        } else {
            System.out.println(leftIndent + parentNode.getName());
        }
    }
 
}

Find below the folder / directory used as input in this example.

3. Run Your Code

Right click on 'FolderTraversar.java' and select from context menu 'Run As' --> 'Java Application'.

4. Console Output

Your code will print the folder structure along with the file names as shown below.

Download SrcCode

All code samples shown in this post are available in the following link RecursiveFolderTraversar.zip

References