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, "");
}
}
Related Questions
drjack9650@gmail.com
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.