Last Updated on 29 July 2019   |   Print Email
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:
List files in the first level.
For each file in the first level list files:
If the file is a directory:
Print out directory name.
Repeat the step 1 and 2 with the current directory.
If the file is a file:
Print out file name.
Continue with next file.
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:
dirPath: Absolute path of the directory being listed.
level: this number is used to indent the output, make the output looks like a hierarchical structure. The method must be invoked with the level = 0.
As you can see, inside the listDirectory() method, there is a call to itself:
Nam Ha Minh is certified Java programmer (SCJP and SCWCD). He began programming with Java back in the days of Java 1.4 and has been passionate about it ever since. You can connect with him on Facebook and watch his Java videos on YouTube.
Can we return the result that is list of all nested sub-directories(not files; only sub-directories and their nested sub-directories) for a given root path instead of displaying/printing it?
Yes, of course. You can modify the above code to return a list of directory objects.
Can we return the result that is list of all nested sub-directories(not files; only sub-directories and their nested sub-directories) for a given root path instead of displaying/printing it?
Comments
Yes, of course. You can modify the above code to return a list of directory objects.