Open In App

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

Last Updated : 26 Jan, 2022
Improve
Improve
Like Article
Like
Save
Share
Report

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.

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

Example 3 –

Below is another iterative program to get all file name using Stack DS

Java




// Iterative Program to get all file names in Directory and
// SubDirectory
 
import java.io.*;
 
class GFG {
    public static void main(String[] args)
    {
        // provide complete path for directory(to be changed
        // accordingly)
        String mainDir = "c:\\GFG\\example";
        // File object
        File file = new File(mainDir);
        Stack<File> s = new Stack<>();
        s.push(file);
        // initially stack is not empty
        System.out.println("Content of Directory " + mainDir
                           + " is");
        while (!s.empty()) {
            File tmpF = s.pop();
            // check if it is a file or not
            if (tmpF.isFile()) {
                // print file name can code here according
                // to our need
                System.out.println(tmpF.getName());
            }
            else if (tmpF.isDirectory()) {
                // It's an directory hence list and push all
                // files in stack
                File[] f = tmpF.listFiles();
                for (File fpp : f) {
                    s.push(fpp);
                }
            } // else if ends here
        } // stack is not empty loop ends here
    } // main function ends here
}


Output:

Content of Directory c:\GFG\example is
example.txt
testTwo.java
testTwo.class
test.java
test.class
test.java
eg1.java
eg1.class
test.java
test.class
Students.java
Students.class

NOTE: The above code won’t compile on online IDE to compile and execute it download in your local system.

 



Like Article
Suggest improvement
Previous
Next
Share your thoughts in the comments

Similar Reads