Introduction

Refer to the 'FolderTree.rar' in the '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:
I have used a recursive function for printing this hierarchy. Let’s understand the flow. Consider the following hierarchy:
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
INPUT
  1. Enter no.of folders: 7 ** * Folder 1 Details ** * Enter Folder ID: 1
  2. Enter Parent Folder ID: 0
  3. Enter Folder Name: Gujarat ** * Folder 2 Details ** * Enter Folder ID: 2
  4. Enter Parent Folder ID: 0
  5. Enter Folder Name: Maharashtra ** * Folder 3 Details ** * Enter Folder ID: 3
  6. Enter Parent Folder ID: 1
  7. Enter Folder Name: Ahmedabad ** * Folder 4 Details ** * Enter Folder ID: 4
  8. Enter Parent Folder ID: 1
  9. Enter Folder Name: Surat ** * Folder 5 Details ** * Enter Folder ID: 5
  10. Enter Parent Folder ID: 2
  11. Enter Folder Name: Mumbai ** * Folder 6 Details ** * Enter Folder ID: 6
  12. Enter Parent Folder ID: 5
  13. Enter Folder Name: Colaba ** * Folder 7 Details ** * Enter Folder ID: 7
  14. Enter Parent Folder ID: 2
  15. Enter Folder Name: Pune
OUTPUT
OUTPUT