使用文件系统层次结构创建树的Java方法

时间:2013-04-24 14:20:42

标签: java arrays string tree apache-zookeeper

我正面临着以下问题,我一直在努力寻找解决方案,但到现在为止我什么也没想到:

我有一个文件系统层次结构,例如:

/HANDLERS/HANDLER1
/HANDLERS/HANDLER2
/HANDLERS/HANDLER3

/MODULES/PROGRAMMING/PROGRAMMER1
/MODULES/PROGRAMMING/PROGRAMMER2
/MODULES/PROGRAMMING/PROGRAMMER3

/MODULES/TESTING/TESTING1
/MODULES/TESTING/TESTING2

等等。

我想创建一个“树”,假设“/”是已经创建的根。并且我附加的图像中显示的结构是目标。

enter image description here

我需要一个名为

的方法
void createNode(String path){

}

在我的要求中,此方法将始终接收完整路径并执行以下操作:

void create(String fullPath){
 //Here I use a method which splits the fullPath into a String array to get every part that will represent a node, for example, if the fullPath is /MODULE/PROGRAMMING/PROHRAMMER1 I use:
String[] singleNodes = separateNodes(fullPath);//I get:MODULE,PROGRAMMING AND PROGRAMMER
//Then I use a loop to iterate the elements

for (String s : singleNodes) {
}
//WHAT CAN I DO HERE?
}

但我不知道如何在循环内部工作,我需要检查节点是否存在,如果存在,我只需要添加缺少的部分,例如,如果我发送/ MODULES / PROGRAMMING / PROGRAMMER1,如果我第一次发送,它将创建整个东西,但如果那时我发送/ MODULES / PROGRAMMING / PROGRAMMER2,它只需要添加PROGRAMMER2。

如果有人可以帮助我,我会提前感谢它,谢谢你。

4 个答案:

答案 0 :(得分:1)

如何将文件路径转换为Java中的层次结构

Node createNode(String path) {
    File location = new File(path);
    File[] children = file.listFiles();
    Node node = new Node(location.getName());

    if(location.isDirectory()) {
        List<Node> children = new ArrayList();
        for(File child : children) {
            children.add(createNode(child.getPath()));
        }
        node.setChildren(children);
    }
    return node;
}

class Node {
    String name;
    List<Node> children;
}

你可以通过createNode(myRoot)

来调用它

答案 1 :(得分:1)

免责声明:未经过测试,没有错误检查,没有getter / setter。

package com.jorge.teste;

import java.util.ArrayList;
import java.util.List;

public class Main {

    public static class Tree<T> {
        Node<T> root;

        public static class Node<T> {
            T data;

            Node<T> parent;

            List<Node<T>> children = new ArrayList<Main.Tree.Node<T>>();

            public Node(final T data, final Node<T> parent) {
                this.data = data;
                this.parent = parent;
            }
        }
    }

    public static Tree<String> tree = new Tree<String>();

    public static void createNode(final String path) {
        String[] parts = path.split("/");
        Tree.Node<String> parent = null;
        for (String part : parts) {
            if (parent == null) {
                if (tree.root == null) {
                    tree.root = new Tree.Node<String>(part, null);
                }
                parent = tree.root;
            } else {
                Tree.Node<String> found = null;
                for (Tree.Node<String> child : parent.children) {
                    if (child.data.equals(part)) {
                        found = child;
                        break;
                    }
                }

                if (found == null) {
                    parent.children.add(found = new Tree.Node<String>(part, parent));
                }

                parent = found;
            }
        }
    }

    public static void main(final String[] args) {
        createNode("/a/b/c");
        createNode("/a/b/c/d");
    }
}

答案 2 :(得分:0)

如果你想坚持你目前的循环,那么你应该尝试这样的事情 (我假设您已经拥有了上述的根节点)

Node currentNode = rootNode; 
for (String s : singleNodes) {
     if( currentNode.hasChild(s) ) currentNode = currentNode.getChild(s);
     else currentNode = currentNode.createChild(s);
}

假设createChild(s)返回创建的Node,它可能不应该。但那不是问题

但是说实话,我不认为这应该使用循环来完成,通常使用递归更好地处理树。

答案 3 :(得分:0)

我最终成功完成了它,符合我的要求,这与我向动物园管理员提出的问题有关。

最好的问候。

public void createNode(NodePath nodePath, NodeData nodeData, NodeRights nodeRights, NodeCreationHandler nodeCreationHandler) throws KeeperException, InterruptedException, ZookeeperCreationException {

        if (zk == null) {
            throw new ZookeeperCreationException("The zookeeper client has not been instanced.");
        }       
        String targetPath = nodePath.getFullNodePath();
        logger.warn("full path: " + targetPath);
        targetPath = targetPath.substring(1, targetPath.length());
        logger.warn("full path mod: " + targetPath);
        byte[] serializedData = nodeData.serialize(new Object());
        String[] array = targetPath.split(ICoordinationConstants.BASE_ROOT_SPTR);
        String acum="";
        for (int i = 0; i < array.length-1; i++) {
            acum+=(ICoordinationConstants.BASE_ROOT_SPTR+array[i]);
            logger.warn("acum: " + acum);
            if (zk.exists(acum, null) == null) {
                logger.warn("It does not exists, proceed to create it...");
                zk.create(acum, serializedData, Ids.OPEN_ACL_UNSAFE, CreateMode.PERSISTENT);
            }
        }
        zk.create(acum+ICoordinationConstants.BASE_ROOT_SPTR+array[array.length-1], serializedData, Ids.OPEN_ACL_UNSAFE, CreateMode.EPHEMERAL);             
    }