我需要創建一個使用 HashMap 來構建檔案樹的樹節點,HashMap 的鍵是路徑,它的值是檔案名。我已經實作了一個代碼,它分解了構建層次結構的鍵值:
public void createNode(HashMap<String, String> map) {
DefaultMutableTreeNode root = new DefaultMutableTreeNode("SQL Scripts");
DefaultTreeModel treeModel = new DefaultTreeModel(root);
tree.setModel(treeModel);
Set<String> keys = map.keySet();
Iterator<String> it = keys.iterator();
while (it.hasNext()) {
String key = it.next();
String value = map.get(key);
String[] path = key.split("/");
DefaultMutableTreeNode parent = root;
for (int i = 0; i < path.length; i ) {
boolean found = false;
int index = 0;
Enumeration e = parent.children();
while (e.hasMoreElements()) {
DefaultMutableTreeNode node = (DefaultMutableTreeNode) e.nextElement();
if (node.toString().equals(path[i])) {
found = true;
break;
}
index ;
}
if (!found) {
DefaultMutableTreeNode child = new DefaultMutableTreeNode(path[i]);
treeModel.insertNodeInto(child, parent, index);
parent = child;
} else {
parent = (DefaultMutableTreeNode) treeModel.getChild(parent, index);
}
}
DefaultMutableTreeNode child = new DefaultMutableTreeNode(value);
treeModel.insertNodeInto(child, parent, parent.getChildCount());
}
}
但是由于某種我無法識別的原因,它不起作用。我仍然得到以下結果:

誰能告訴我我在代碼實作上做錯了什么?
uj5u.com熱心網友回復:
問題似乎是您試圖使用 拆分 Windows 檔案路徑/,除了 Windows 檔案路徑由 分隔\,這當然也是正則運算式的轉義字符??
你可以...
用于key.replace(File.separatorChar, '/').split("/")更改\to/和 split 就可以了
或者...
File file = new File(key);
Path path = file.toPath();
// Path path = Paths.get(key);
for (int index = 0; index < path.getNameCount(); index ) {
String subPath = path.getName(index));
//...
}
或者...
File file = new File(key);
Path path = file.toPath();
// Path path = Paths.get(key);
Iterator<Path> it = path.iterator();
while (it.hasNext()) {
Path next = it.next();
String subPath = path.getFileName();
//...
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/482334.html
上一篇:有沒有辦法在文本欄位中設定所有結果值?它只按預期設定最后一個值,但我希望全部設定在resultTextField
