java - java中的unix ls命令

标签 java tree

嗨,我正在尝试在 java 中以 unix“ls”命令样式列出文件夹。 我有一个像这样的文件夹树:

enter image description here

我的文件结构如下:

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/

相关文章:

sql - 如何使 SQL 根据具有相同标签的项目创建标签层次结构?

c++ - 具有多个子节点的树的广度优先打印

java - 当调用 IntBinaryOperator 的新实例时,ApplyAsInt 如何自动工作?

java - 耶拿;迭代父类(super class)时出现java堆空间错误

java - 如何在android中制作xml格式的表格数据

algorithm - 是否有一种算法可以在有向有根树(树状结构)中找到最小成本路径?

java - 通过java获取网页

java - 带有提供特定返回值的抽象方法的未经检查的强制转换警告

java - 有什么办法可以查看原始类型的 HashCode?

algorithm - 关于 Ukkonen 的后缀树的说明