Print all nested directories and files in a given directory – Recursion

Given a source directory, write a recursive program to print all the nested directories and files in the source directory.

Example:

[Hellojava]
	[target]
		original-Hellojava-1.0-SNAPSHOT.jar
		[classes]
			[com]
				[example]
					[lambda]
						[demo]
							Hello.class
				[maven-archiver]
			pom.properties
		Hellojava-1.0-SNAPSHOT.jar
	pom.xml
	Hellojava.iml
		[src]
		[test]
			[java]
		[main]
			[resources]
			[java]
				[com]							
                                                        Hello.java

Approach:

  1. Check if given file is directory, 
    1. if yes then print its name.
    2.  Iterate through all the files inside the directory
      1. If the current file is a directory then make a recursive call for directory
      2. If the current file is not directory then print the file name. 
  2. Else print the file name.
  3. See the code below for better understanding.

NOTE: with every recursive call, add tab space for better printing of hierarchy of files.

Complete Code:

Output:

[Hellojava]
	[target]
		original-Hellojava-1.0-SNAPSHOT.jar
		[classes]
			[com]
				[example]
					[lambda]
						[demo]
							Hello.class
				[maven-archiver]
			pom.properties
		Hellojava-1.0-SNAPSHOT.jar
	pom.xml
	Hellojava.iml
		[src]
		[test]
			[java]
		[main]
			[resources]
			[java]
				[com]							
                                                        Hello.java