Technologies used in this article :

  1. JDK 1.6

  2. Eclipse 3.7

JDK 1.6 Installer : Download
Eclipse 3.7 Installer : Download

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.

To know how to create a java project in Eclipse IDE, go through the following tutorial "Java Hello World Example using Eclipse IDE".

Sample project structure is shown below

Sample project structure


2. Write Code

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

File :
package com.srccodes.example;


 * @author
 * @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.

Sample project structure


3. Run Your Code

Right click on '' 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.

Console Output


Download Source Code