Refer the 'FolderTree.rar' in 'Download Files' section above for the code.
In this blog, I will demonstrate Java code to print the folder tree or folder hierarchy or what you can call a directory structure.
I have used class objects array as a data structure to store the information regarding the folders. An Array List of integers is used to store visited indexes and a variable named ‘tab’ to give tab spaces.
The Flow is basically like this:
- First, it asks to enter the number of folders and we enter the number of folders.
- For each folder, we enter Folder ID, folder’s Parent ID and Folder name.
- After entering these details for each folder, folder hierarchy gets displayed.
I have used recursive function for printing this hierarchy. Let’s understand the flow. Consider the following hierarchy:
So, according to this we will design table like,
Folder ID |
Parent Folder ID |
Folder Name |
1 |
0 |
Gujarat |
2 |
0 |
Maharashtra |
3 |
1 |
Ahmedabad |
4 |
1 |
Surat |
5 |
2 |
Mumbai |
6 |
5 |
Colaba |
7 |
2 |
Pune |
- The method print() will first print the root node.
- In for loop, the folders array is traversed from current index to the last index to check if the current node’s ID is any of the folder’s Parent ID.
- If the condition satisfies, the folder name is printed and the print() method is called again recursively to check and print the folder’s child and so on..
- visitedIndexes list contains the indexes of already visited and printed nodes, so that the loop won’t run for the folder unnecessarily.
INPUT
Enter no. of folders: 7
*** Folder 1 Details ***
Enter Folder ID : 1
Enter Parent Folder ID : 0
Enter Folder Name : Gujarat
*** Folder 2 Details ***
Enter Folder ID : 2
Enter Parent Folder ID : 0
Enter Folder Name : Maharashtra
*** Folder 3 Details ***
Enter Folder ID : 3
Enter Parent Folder ID : 1
Enter Folder Name : Ahmedabad
*** Folder 4 Details ***
Enter Folder ID : 4
Enter Parent Folder ID : 1
Enter Folder Name : Surat
*** Folder 5 Details ***
Enter Folder ID : 5
Enter Parent Folder ID : 2
Enter Folder Name : Mumbai
*** Folder 6 Details ***
Enter Folder ID : 6
Enter Parent Folder ID : 5
Enter Folder Name : Colaba
*** Folder 7 Details ***
Enter Folder ID : 7
Enter Parent Folder ID : 2
Enter Folder Name : Pune
OUTPUT