Skip to content
Related Articles

Related Articles

Improve Article
Save Article
Like Article

Java Program to List all Files in a Directory and Nested Sub-Directories

  • Difficulty Level : Hard
  • Last Updated : 09 Oct, 2021

Prerequisites: File class

Given a main directory/folder, list all the files from it, and if this directory has other nested sub-directories, list files from them. It is pretty easy to observe a simple recursion pattern in the above problem.

Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more,  please refer Complete Interview Preparation Course.

Algorithm : 

  1. Create a File object for the main directory.
  2. Get an array of files for the main directory.
  3. If array[i] is a file:
    • Print out the file name.
  4. If array[i] is a directory :
    • Print out directory name.
    • Get array of files for current sub-directory.
    • Repeat the step 3 and 4 with current sub-directory.
  5. Repeat the step 3 and 4 with next array[i].

Example 1:



Java




// Java program to print all files
// in a folder(and sub-folders)
  
import java.io.File;
  
public class GFG {
    static void RecursivePrint(File[] arr, int index, int level)
    {
        // terminate condition
        if (index == arr.length)
            return;
  
        // tabs for internal levels
        for (int i = 0; i < level; i++)
            System.out.print("\t");
  
        // for files
        if (arr[index].isFile())
            System.out.println(arr[index].getName());
  
        // for sub-directories
        else if (arr[index].isDirectory()) {
            System.out.println("[" + arr[index].getName()
                               + "]");
  
            // recursion for sub-directories
            RecursivePrint(arr[index].listFiles(), 0,
                           level + 1);
        }
  
        // recursion for main directory
        RecursivePrint(arr, ++index, level);
    }
  
    // Driver Method
    public static void main(String[] args)
    {
        // Provide full path for directory(change
        // accordingly)
        String maindirpath
            = "C:\\Users\\Gaurav Miglani\\Desktop\\Test";
  
        // File object
        File maindir = new File(maindirpath);
  
        if (maindir.exists() && maindir.isDirectory()) {
              
              // array for files and sub-directories
            // of directory pointed by maindir
            File arr[] = maindir.listFiles();
  
            System.out.println(
                "**********************************************");
            System.out.println(
                "Files from main directory : " + maindir);
            System.out.println(
                "**********************************************");
  
            // Calling recursive method
            RecursivePrint(arr, 0, 0);
        }
    }
}

Output: 

**********************************************
Files from main directory : C:\Users\Gaurav Miglani\Desktop\Test
**********************************************
Cormen.pdf
Extra-Items.pdf
XYZ.pdf
[Docs]
    A.docx
    B.doc
    C.docx
ABC.pdf
JKL.pdf
[sheets]
    XXX.csv
    YYY.csv
results.pdf
[Resumes]
    [Before2016]
        Resume2015.doc
        Resume2016.doc
        [Before2014]
            Resume2014.doc
    Resume2017.doc
    Resume2017.pdf
        QA.doc
Testing.pdf

Example 2: Below is another recursive program. Here we use recursion only for nested sub-directories. For main directory files, we use foreach loop.

Java




// Recursive Java program to print all files
// in a folder(and sub-folders)
  
import java.io.File;
  
public class GFG {
    static void RecursivePrint(File[] arr, int level)
    {
        // for-each loop for main directory files
        for (File f : arr) {
            // tabs for internal levels
            for (int i = 0; i < level; i++)
                System.out.print("\t");
  
            if (f.isFile())
                System.out.println(f.getName());
  
            else if (f.isDirectory()) {
                System.out.println("[" + f.getName() + "]");
  
                // recursion for sub-directories
                RecursivePrint(f.listFiles(), level + 1);
            }
        }
    }
  
    // Driver Method
    public static void main(String[] args)
    {
        // Provide full path for directory(change
        // accordingly)
        String maindirpath
            = "C:\\Users\\Gaurav Miglani\\Desktop\\Test";
  
        // File object
        File maindir = new File(maindirpath);
  
        if (maindir.exists() && maindir.isDirectory()) {
            // array for files and sub-directories
            // of directory pointed by maindir
            File arr[] = maindir.listFiles();
  
            System.out.println(
                "**********************************************");
            System.out.println(
                "Files from main directory : " + maindir);
            System.out.println(
                "**********************************************");
  
            // Calling recursive method
            RecursivePrint(arr, 0);
        }
    }
}

Output: 

**********************************************
Files from main directory : C:\Users\Gaurav Miglani\Desktop\Test
**********************************************
Cormen.pdf
Extra-Items.pdf
XYZ.pdf
[Docs]
    A.docx
    B.doc
    C.docx
ABC.pdf
JKL.pdf
[sheets]
    XXX.csv
    YYY.csv
results.pdf
[Resumes]
    [Before2016]
        Resume2015.doc
        Resume2016.doc
        [Before2014]
            Resume2014.doc
    Resume2017.doc
    Resume2017.pdf
        QA.doc
Testing.pdf

This article is contributed by Gaurav Miglani. If you like GeeksforGeeks and would like to contribute, you can write an article using write.geeksforgeeks.org or mail your article to review-team@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks. Please write comments if you find anything incorrect or you want to share more information about the topic discussed above.




My Personal Notes arrow_drop_up
Recommended Articles
Page :

Start Your Coding Journey Now!