I need to return or print a file/directory tree using stack data structure. For example:
Folder1
Folder1.1
File1.1.1
Folder1.2
Folder2
File2.1
File2.2
...
My code so far:
public static void filetree(File mainfolder, int indent){
Stack<String> filesanddirectories = new Stack<>();
for (File file : mainfolder.listFiles()){
if (file.isDirectory()){
filesanddirectories.push(file.getName());
filetree(file, 0);
}
else if (file.isFile()){
filesanddirectories.push(file.getName());
}
}
for (int i = 0; i < filesanddirectories.size(); i++){
System.out.println(filesanddirectories.pop());
}
}
This code prints folders and files but with no indention, backwards and not exactly in the right order.
Could someone explain the logic of how it should work?
EDIT: Found a solution using recursion and stack (although stack seems to be unnecessary)
indentvalue every time you recurse - something likefiletree(file, 0);->filetree(file, indent + 4);. You will then need to change your printing mechanism to use theindentvalue.if (file.isFile()){filesanddirectories.push(file.getName());->if (file.isFile()){System.out.println(....