【问题标题】:Algorithm for converting directory tree (.txt file) to JTree将目录树(.txt 文件)转换为 JTree 的算法
【发布时间】:2015-08-07 08:37:13
【问题描述】:

我正在制作一个程序,它将生成一个包含目录树的文本文件。我已经完成了文件遍历部分,所以我准备好了我的文本文件。然后我想使用这个文本文件,读取它并将数据转换为 JTree。我已经坚持算法 2 天了!!有人有什么建议吗?请帮忙。

*请注意,我使用"\t" 作为间距。

我的 path.txt 的某些部分

路径.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

这是我迄今为止尝试过的:

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) {
    }

}

}

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

我的代码问题似乎是在它完成探索文件夹后,实际行不知道它,并继续阅读下一行,即探索文件夹中的文件。 (很难用语言来解释,对不起我的英语不好)

第二个问题是它不会读取每个主文件夹,如图所示,程序在完成探索“Arcana Advanced”文件夹后停止工作。我理解这个问题的原因,所以我尝试了另一种方法来检查它们有多少个主文件夹,并执行一个 for 循环。但这非常麻烦和耗时,有没有更简单的方法来做到这一点?

【问题讨论】:

  • 我建议发布您遇到特定问题的代码。

标签: java algorithm swing jtree


【解决方案1】:

这是我的解决方案:(请注意,当我复制并粘贴您的文件时,我最终用 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();
        }
    }

【讨论】:

  • 谢谢!我从您的代码中获得了一些想法,并尝试将其更改为我自己的方式!
【解决方案2】:

我现在无法编写正确的 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 () ;
        }
    }
}

【讨论】:

  • 我不太习惯 Stack 类,也不想乱用它。顺便说一句,谢谢!
  • @KongponCharanwattanakit 和WillShackleford的思路基本一样,我只是简单的用一个Stack来存储当前节点的父节点。如果您可以在树中上升(通过使用getParent),那么您不需要 WillShackleford 帖子中显示的 Stack。
【解决方案3】:

终于,我的问题得到了解决方案。

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);
        }
    }




}

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-26
    • 2021-12-24
    • 2017-02-09
    • 2017-09-23
    相关资源
    最近更新 更多