首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> Java 程式設計 >> Java 相關知識

Java 實現本地文件系統瀏覽器:JTree 遞歸構建目錄樹

     編輯:Java 相關知識

本文提供一個基於 Swing JTree 的本地文件系統瀏覽器完整實現。核心邏輯採用遞歸遍歷目錄,構建 DefaultMutableTreeNode 樹模型,支持從控制台輸入根路徑動態加載,並展示圖標與滾動面板。代碼分為樹模型構建類 FilePathObj 與主界面類 PathTree 兩部分。

1. 遞歸構建樹模型:FilePathObj

package com.swing.tree;
import java.io.File;
import javax.swing.tree.DefaultMutableTreeNode;

public class FilePathObj {
    private DefaultMutableTreeNode root;

    public DefaultMutableTreeNode getPathObj() {
        return (root != null) ? root : new DefaultMutableTreeNode("null NODE");
    }

    public FilePathObj(String path) {
        try { root = buildTree(path); }
        catch (Exception e) { e.printStackTrace(); }
    }

    private DefaultMutableTreeNode buildTree(String dir) throws Exception {
        File file = new File(dir);
        if (!file.exists()) throw new Exception("file name is null");

        if (file.isFile()) return new DefaultMutableTreeNode(file.getAbsolutePath());

        File[] children = file.listFiles();
        DefaultMutableTreeNode node = new DefaultMutableTreeNode(file.getAbsolutePath());
        if (children == null || children.length == 0) return node;

        for (File child : children) {
            if (child.isDirectory())
                node.add(buildTree(child.getAbsolutePath())); // 遞歸
            else
                node.add(new DefaultMutableTreeNode(child.getAbsolutePath()));
        }
        return node;
    }
}

2. 主界面與交互:PathTree

package com.tree;
import javax.swing.*;
import javax.swing.tree.*;
import java.awt.*;
import java.io.*;
import com.swing.tree.FilePathObj;

public class PathTree extends JFrame {
    public static void main(String[] args) {
        try {
            BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
            String path;
            File f;
            System.out.print("輸入要顯示的文件路徑: ");
            while ((path = in.readLine()) != null) {
                f = new File(path);
                if (!f.exists() || f.isFile()) {
                    System.out.println("請輸入正確的目錄路徑");
                    continue;
                }
                new PathTree(path).setVisible(true);
                break;
            }
        } catch (Exception e) { e.printStackTrace(); }
    }

    public PathTree(String path) {
        super("Creating a Simple JTree");
        FilePathObj obj = new FilePathObj(path);
        JTree tree = new JTree(obj.getPathObj());
        tree.setCursor(new Cursor(Cursor.HAND_CURSOR));

        Container cp = getContentPane();
        cp.setLayout(new FlowLayout());
        cp.add(new JScrollPane(tree), BorderLayout.CENTER); // 可滾動
        setSize(275, 500);
        pack();
    }
}

3. 關鍵點與擴展方向

  • 遞歸終止條件:文件節點直接創建葉子節點;目錄節點遞歸構建子樹。
  • 異常處理:路徑不存在、權限不足等情況拋出異常,上層捕獲打印堆疊。
  • UI 增強:可為文件/目錄設置不同圖標 (DefaultTreeCellRenderer)、添加右鍵菜單(打開、刪除、屬性)、集成文件過濾器、支持拖拽操作。
  • 性能優化:大目錄遞歸可能導致棧溢出或界面凍結,建議採用 懶加載 (TreeWillExpandListener 動態加載子節點) 或後台線程預載入。

此示例可作為文件管理器、代碼瀏覽器、資源選擇器等桌面應用的基礎模組。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved