Java program to List all files in a directory and nested sub-directories | Recursive approach

Prerequisites : File class

Given a main directory/folder, list all the files from it and if this directory have other nested sub-directories, list files from them also.

It is quite easy to observe simple recursion pattern in above problem.

Recursive Algorithm :

1. Create File object for main directory.
2. Get array of files for main directory.
3. If array[i] is a file :
   -> Print out 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].
// 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 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

 

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

// 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 also write an article using contribute.geeksforgeeks.org or mail your article to contribute@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.

GATE CS Corner    Company Wise Coding Practice

Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



0 Average Difficulty : 0/5.0
No votes yet.