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:

a directory

To list all sub files and sub directories nested in all levels, one solution is to use recursion algorithm:

  1. List files in the first level.
  2. For each file in the first level list files:
    1. If the file is a directory:
      • Print out directory name.
      • Repeat the step 1 and 2 with the current directory.
    2. If the file is a file:
      • Print out file name.
    3. 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:

 

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:

output screenshot

 

Related File IO Tutorials:

 

Other Java File IO Tutorials:


About the Author:

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.



Attachments:
Download this file (ListDirectoryRecurisve.java)ListDirectoryRecurisve.java[sample program]0.8 kB

Add comment

   


Comments 

#3Nam2016-07-04 04:46
Quoting Swapnil Joshi:
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.
Quote
#2Swapnil Joshi2016-06-28 17:47
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?
Quote
#1Swapnil Joshi2016-06-28 17:42
What if I want to return this directory structure instead of displaying/printing it? How do I return it in a list object?
Quote