Loop Through a Given Directory With Indentation in Java

The code below provide a method for recursively loop through a directory in Java. It also prints out the directory hierarchy with indentation.

package com.programcreek;
import java.io.File;
import org.apache.commons.lang3.StringUtils;
public class LoopThroughADirectory {
	public static void main(String[] args) {
	    File[] files = new File("/home/programcreek/Desktop").listFiles();
	public static void showFiles(File[] files) {
	    for (File file : files) {
	        if (file.isDirectory()) {
	        	printIndent(StringUtils.countMatches(file.getAbsolutePath(), "/")-3);
	            System.out.println("Directory: " + file.getName());
	            showFiles(file.listFiles()); // recursively call itself
	        } else {
	        	printIndent(StringUtils.countMatches(file.getAbsolutePath(), "/")-3);
	            System.out.println("File: " + file.getName());
	public static void printIndent(int count){
		for(int i=0; i<count; i++){


—–Directory: log4j
———-File: log.out
———-File: filec.out
———-File: fileb.out
———-File: filea.out
—–File: file1
—–File: file2

Leave a Comment