Academic Integrity: tutoring, explanations, and feedback — we don’t complete graded work or submit on a student’s behalf.

Implement an operating system command that displays the tree structure of a fold

ID: 646474 • Letter: I

Question

Implement an operating system command that displays the tree structure of a folder or directory in java. The program should ask the user to enter a folder name. The program must also use the java.io.file api. Then, the program will traverse the tree hierarchy of the folder in a preorder traversal to retrieve the children folders or files in the specified folder. As the hierarchy is being traversed, the names of the subfolders or files are being displayed in an indented fashion where the amount of indentation reflects the hierarchy level of the displayed subfolders or files.

Explanation / Answer

package com.srccodes.example;

import java.io.File;

/**
* @author paramesh
*
*/
public class Folder {

   /**
   * @param args
   */
   public static void Foldertraverse(File parentNode, String indentationLeft) {
       if (parentNode.isDirectory()) {
           System.out.println(indentationLeft + parentNode.getName());
           // Use left padding to create tree structure in the console output.
           indentationLeft += " ";
           File childNodes[] = parentNode.listFiles();
           for (File childNode : childNodes) {
               Foldertraverse(childNode, indentationLeft);
           }
       } else {
           System.out.println(indentationLeft + parentNode.getName());
       }
   }
   // Entering folder that you want
   public static void main(String[] args) {
       File folder = new File("c:/myFolder");
       Foldertraverse(folder, "");
   }
}

Hire Me For All Your Tutoring Needs
Integrity-first tutoring: clear explanations, guidance, and feedback.
Drop an Email at
drjack9650@gmail.com
Chat Now And Get Quote