简体   繁体   English

将目录树(.txt文件)转换为JTree的算法

[英]Algorithm for converting directory tree (.txt file) to JTree

I'm making a program that will generate a text file that contains directories tree. 我正在制作一个程序,它将生成一个包含目录树的文本文件。 I've done the file walking part, so I got my text file ready. 我已经完成了文件遍历部分,因此我准备好了文本文件。 Then I want to use this text file, read it and convert the data in to JTree. 然后,我想使用此文本文件,读取它并将数据转换为JTree。 I've been stucking with the algorithm for 2 days!! 我已经坚持了2天的算法! Does anyone has some suggestions? 有人有建议吗? plase help. 请帮助。

*note that I used "\\t" for the spacing. *请注意,我使用"\\t"作为间隔。

Some part of my path.txt 我的path.txt的某些部分

path.txt path.txt

Arcana Advanced
        ABC
        ABC
        AcnMiniGame
        client
        Data
        error
        patch
        patch_03451
        patch_03452
        patch_03453
        patch_03454
        patch_03455
        patch_03456
        patch_03458
        SaveDeck
                ModifiedDeck1 Earth Water
                ModifiedDeck2 Wind Fire
                ModifiedDeck3 Wind Earth
                ModifiedDeck4 Earth Fire
                ModifiedDeck5 Wind Water
                ModifiedDeck6 Fire Water
                Starter1 Earth Water
                Starter2 Fire Wind
                Starter3 Earth Wind
                Starter4 Earth Fire
                Starter5 Water Wind
                Starter6 Water Fire
        Tutorial
        unicows
        unins000
        unins000
ASActiveX
        Au_activeX
                ThaiGameStart
        nProtect
                npkcx
                        npkagt
                        npkcrypt
                        npkcrypt
                        npkcrypt
                        npkcsvc
                        npkcusb
                        npkcx
                        npkcx
                        npkpdb
                        npkuninst

This is what I've tried so far: 到目前为止,这是我尝试过的:

public final class FileTree extends JPanel {


JTree tree;
DefaultMutableTreeNode root;
Path path;
List<String> lines;

public FileTree(String filepath) {
    try {
        root = new DefaultMutableTreeNode("root", true);
        this.path = Paths.get(filepath);
        lines = Files.readAllLines(path);
        getList(root, 0);
        setLayout(new BorderLayout());
        tree = new JTree(root);
        tree.setRootVisible(false);
        add(new JScrollPane((JTree) tree), "Center");
    } catch (IOException ex) {
        Logger.getLogger(FileTree.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public int getTab(int line) {
    String text = lines.get(line);
    return text.lastIndexOf("\t");

}

public boolean noChild(int line) {
    if (getTab(line) < getTab(line + 1)) {
        return false;
    }
    return true;

}

public int getLastLine(int line) {
    int myTab = getTab(line);
    int myLine = line+1;
    int i = line+1;
    while (true) {
        if (myTab == getTab(myLine)) {
            return i;
        } else {
            myLine++;
            i++;
        }
    }
}

public int getChildList(int line) {
    int i = 0;
    int ChildTab = getTab(line + 1);
    int myLine = line + 1;
    while (true) {
        if (ChildTab == getTab(myLine)) {
            myLine++;
            i++;
        } else if (ChildTab < getTab(myLine)) {
            myLine++;
        } else if (ChildTab > getTab(myLine)) {
            return i;
        }
    }
}



public void getList(DefaultMutableTreeNode node, int line) {
    try {
        if (noChild(line)) {
            System.out.println("FILE  -  " + lines.get(line));
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(lines.get(line).trim());
            node.add(child);
        } else {
            System.out.println("DIRECTORY  -  " + lines.get(line));
            DefaultMutableTreeNode child = new DefaultMutableTreeNode(lines.get(line).trim());
            node.add(child);
            int ChildList = getChildList(line);
            for (int i = 0; i < ChildList; i++) {
                getList(child, line + i + 1);
            }

        }
    } catch (Exception e) {
    }

}

} }

the result: http://www.uppic.org/image-5E7B_55C470B7.jpg 结果: http : //www.uppic.org/image-5E7B_55C470B7.jpg

My code problem seems to be that after it finished exploring the folder, the actual line doesn't know it, and keep reading the next line which is the file in the explored folder. 我的代码问题似乎是在完成浏览文件夹后,实际的行不知道它,并继续读取下一行,即浏览文件夹中的文件。 (It's hard to explain in words, sorry for my bad English) (很难用语言解释,对不起我的英语不好)

And the second problem is it doesn't read every primary folder, as you can see in the picture, the program stops working after finished exploring "Arcana Advanced" folder. 第二个问题是它无法读取每个主文件夹,如您在图片中看到的那样,该程序在浏览完“ Arcana Advanced”文件夹后停止工作。 I understand the reason for this problem, so I tried to make another method to check how many primary folders are they, and do a for loop. 我知道此问题的原因,所以我尝试制作另一种方法来检查它们有多少个主文件夹,并进行for循环。 But that is very messy and time-consuming, anyone has any simpler method to do that ? 但这是非常麻烦且耗时的,任何人都有更简单的方法来做到这一点吗?

I cannot write correct Java code right now, but here is some pseudo code that should work: 我现在无法编写正确的Java代码,但是以下一些伪代码应该可以使用:

File f = new File () ;
Stack s = new Stack () ;
Node r = new Root () ;
int nTabs = 0 ; // Current number of tabs
while (f) { // while there are remaining lines in f
    String line = f.readLine () ;
    int n = countTabs (line) ;
    if (nTabs == n) {
        r.addChild (new Node(line)) ;
    }
    else if (nTabs == n + 1) {
        Node node = new Node(line) ;
        r.addChild (node) ;
        s.push(r) ;
        r = node ;
        nTabs = nTabs + 1 ;
    }
    else {
        while (n < nTabs) {
            nTabs = nTabs - 1;
            r = s.pop () ;
        }
    }
}

This was my solution: (Note when I copy and pasted your file I ended up with 8 spaces replacing each tab.) 这是我的解决方案:(请注意,当我复制并粘贴文件时,最后用8个空格替换每个选项卡。)

    public void LoadTree(String filename, JTree tree) {

        try (BufferedReader br = Files.newBufferedReader(Paths.get(filename))) {
            int last_tab_length = -1;
            String line;
            DefaultMutableTreeNode parentNode = new DefaultMutableTreeNode("root");
            DefaultMutableTreeNode lastNode = parentNode;
            DefaultTreeModel model = new DefaultTreeModel(parentNode);
            tree.setModel(model);
            while ((line = br.readLine()) != null) {
                int tab_length = 0;
                while (line.startsWith("\t")) {
                    tab_length++;
                    line = line.substring(1);
                }
                String eightSpaces = "        ";
                while (line.startsWith(eightSpaces)) {
                    tab_length++;
                    line = line.substring(eightSpaces.length());
                }
                DefaultMutableTreeNode node = new DefaultMutableTreeNode(line.trim() + ":" + tab_length);

                if (tab_length > last_tab_length) {
                    parentNode = lastNode;
                }
                for (int i = last_tab_length; i > tab_length; i--) {
                    parentNode = (DefaultMutableTreeNode) parentNode.getParent();
                }
                parentNode.add(node);
                last_tab_length = tab_length;
                lastNode = node;
            }
        } catch (IOException ex) {
            ex.printStackTrace();
        }
    }

Finally, I got a solution for my question. 最后,我为我的问题找到了解决方案。

public final class FileTree extends JPanel {

JTree tree;
DefaultMutableTreeNode root;
Path path;
List<String> lines;

public FileTree(String filepath) {
    try {
        root = new DefaultMutableTreeNode("root", true);
        this.path = Paths.get(filepath);
        lines = Files.readAllLines(path);
        getList(root, 0);
        setLayout(new BorderLayout());
        tree = new JTree(root);
        tree.setRootVisible(false);
        add(new JScrollPane((JTree) tree), "Center");
    } catch (IOException ex) {
        Logger.getLogger(FileTree.class.getName()).log(Level.SEVERE, null, ex);
    }
}

public int getTab(int line) {
    String text = lines.get(line);
    return text.lastIndexOf("\t");

}

public boolean noChild(int line) {
    if (getTab(line) < getTab(line + 1)) {
        return false;
    }
    return true;

}


public TreeNode getNewNode(int line, int line2, DefaultMutableTreeNode node) {
    TreeNode treenode = node;
    int time = getTab(line) - getTab(line2);
    for (int i = 0; i < time; i++) {
        treenode = treenode.getParent();
    }
    return treenode;

}

public void getList(DefaultMutableTreeNode node, int line) {
    DefaultMutableTreeNode child = new DefaultMutableTreeNode(lines.get(line).trim());
    node.add(child);
    if (line + 1 > lines.size() - 1) {
        System.out.println("Finished");
        return;
    }
    if (!noChild(line)) { // have Children
        getList(child, line + 1);
    } else {             // no Children
        if (getTab(line) > getTab(line + 1)) {
            getList((DefaultMutableTreeNode) getNewNode(line, line + 1, node), line + 1);
        } else if (getTab(line) == getTab(line + 1)) {
            getList(node, line + 1);
        }
    }




}

} }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM