The article How to list files and directories in a directory explains very well about how to list all files and directories under a specific directory, however its examples are only for listing the first level files and directories (those which are directly under the parent directory). But a directory may contain many sub files and sub directories which are nested in many levels, as in the following screenshot, for example:
To list all sub files and sub directories nested in all levels, one solution is to use recursion algorithm:
The following method implements the above algorithm:
public void listDirectory(String dirPath, int level) { File dir = new File(dirPath); File[] firstLevelFiles = dir.listFiles(); if (firstLevelFiles != null && firstLevelFiles.length > 0) { for (File aFile : firstLevelFiles) { for (int i = 0; i < level; i++) { System.out.print("\t"); } if (aFile.isDirectory()) { System.out.println("[" + aFile.getName() + "]"); listDirectory(aFile.getAbsolutePath(), level + 1); } else { System.out.println(aFile.getName()); } } } }
The listDirectory() method has two parameters:
As you can see, inside the listDirectory() method, there is a call to itself:
listDirectory(aFile.getAbsolutePath(), level + 1);
That’s the point which makes the entire nested sub files and sub directories listed.
Here is a sample program:
import java.io.File; /** * * @author www.codejava.net * */ public class ListDirectoryRecurisve { public void listDirectory(String dirPath, int level) { File dir = new File(dirPath); File[] firstLevelFiles = dir.listFiles(); if (firstLevelFiles != null && firstLevelFiles.length > 0) { for (File aFile : firstLevelFiles) { for (int i = 0; i < level; i++) { System.out.print("\t"); } if (aFile.isDirectory()) { System.out.println("[" + aFile.getName() + "]"); listDirectory(aFile.getAbsolutePath(), level + 1); } else { System.out.println(aFile.getName()); } } } } public static void main(String[] args) { ListDirectoryRecurisve test = new ListDirectoryRecurisve(); String dirToList = System.getProperty("user.home") + File.separator + "Documents"; test.listDirectory(dirToList, 0); } }
The sample program lists all files and directories in the user’s Documents directory. The output looks like as the following screenshot: