Java - Recursively list all files and subdirectories in directory

Posted on October 20, 2016


In java File class is used to represent the file/directory on a disk. Using the File class we can

  • Check weather a file or directory exist.
  • List all files in a directory.
  • Delete and rename file.
  • Check absolute and relative path of file etc.

 In this section, we will show you how to traverse files and subdirectories in  a directory.

FileDirectoryExample.java

package com.boraji.tutorial;
/**
 * @author imssbora
 *
 */
import java.io.File;

public class FileDirectoryExample {
	public static void main(String[] args) {
		File root=new File("D:/Work/Java");
		showFileAndDirectory(root, 0);
	}

	private static void showFileAndDirectory(File dirPath, int intend) {
		String dirIntend=getTextIntend(intend);
		
		/*Print Directory Name*/
		System.out.println(dirIntend+dirPath.getName()+"/");
		
		File[] files=dirPath.listFiles();
		/*Recursion for Directories*/
		for (File file : files) {
			if(file.isDirectory()){
				showFileAndDirectory(file, intend+1);
			}
		}
		
		/*Print File Name*/
		for (File file : files) {
			if(file.isFile()){
				String fileIntend=getTextIntend(intend+2);
				System.out.println(fileIntend+file.getName());
			}
		}
	}
	
	private static String getTextIntend(int intend){
		StringBuilder builder=new StringBuilder();
		for (int i = 0; i < intend; i++) {
			builder.append(" |--");
		}
		return builder.toString();
	}
}

Output

Java/
 |--bin/
 |-- |--com/
 |-- |-- |--boraji/
 |-- |-- |-- |--tutorail/
 |-- |-- |-- |-- |-- |--Calculator.class
 |-- |-- |-- |-- |-- |--HelloWorld.class
 |--src/
 |-- |--com/
 |-- |-- |--boraji/
 |-- |-- |-- |--tutorail/
 |-- |-- |-- |-- |-- |--Calculator.java
 |-- |-- |-- |-- |-- |--HelloWorld.java