[英]Using stack to make file/directory tree in Java
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) 编辑:找到了使用递归和堆栈的解决方案(尽管堆栈似乎是不必要的)
I used indent
and temp
variables to keep the indent when traversing recursively through the file directory. 在通过文件目录递归遍历时,我使用了
indent
和temp
变量来保持缩进。 Then printed indent at the start of the for
loop. 然后在
for
循环的开始处打印缩进。
public static void filetree(File mainfolder, int indent) {
int temp;
for (File file : mainfolder.listFiles()) {
for(int i = 0; i<indent; i++) {
System.out.print(" ");
}
temp = indent;
if (file.isDirectory()) {
indent++;
System.out.println(file.getName());
filetree(file, indent);
indent--;
} else if (file.isFile()) {
System.out.println(file.getName());
indent = temp;
}
}
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.