【发布时间】: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