嗨,我正在尝试在 java 中以 unix“ls”命令样式列出文件夹。 我有一个像这样的文件夹树:
我的文件结构如下:
private class Node{
public List<Node> children= new ArrayList<Node>();
public String value;
public Node(String value){
this.value = value;
}
public void addSubDirectory(Node child){
children.add(child);
}
}
问题:当命令中“*”后面没有任何内容时,我无法递归超过当前文件夹的子级
例如。命令
ls A/B/*/*/E/ and ls A/*/*/M/*/E/ works
但是命令“ls A/* ”仅显示
B Y
要遍历的代码
public void showCommand(Node root, String command){
String argument = command.substring(3);
System.out.println("command is ls "+argument);
show(root,argument);
}
private void show(Node root, String cmd){
int N = cmd.length();
if(N==0){
// case when end of command is reached
for(Node child:root.children){
System.out.println(child.value);
}
}else{
char c = cmd.charAt(0);
// case when folder name is present in command
if((c!='*') && (c!='/')){
for(Node child:root.children){
if(child.value.equals(String.valueOf(c))){
show(child,cmd.substring(1));
}
}
return;
}else if(c=='*'){
// case when * is present in command
// i think problem lies here
if(N==1){
System.out.println(root.value);
preOrderTraverse(root);
}else{
for(Node child:root.children){
show(child,cmd.substring(1));
}
}
return;
}else if(c=='/'){
// case when '/' is present in commmand
show(root,cmd.substring(1));
return;
}
}
}
最佳答案
当命令中的最后一个字符是 * 时,您将使用空 cmd 回调 showCommand
方法,并且当该方法接收到空 cmd 字符串时,递归将停止。
当当前字符c
是*时,你应该检查它是cmd
中的最后一个字符,如果是那么你应该发送当前cmd
而不是 cmd.substring(1)
。这样它应该递归地遍历层次结构。
关于java - java中的unix ls命令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24588015/