0

I am trying to create a JTree of a file system by giving the path of rootfolder, But at first I am trying to create and print nodes upto the leaf node by recursion.

below is my code ,I am not getting why is it not printing after 1st level, perhaps it is not calling createTree() recursively...can someone tell me how to make it work?(int i=0 is declared outside method)

public void createTree(String rootPath)
{
    rootNode=new DefaultMutableTreeNode(rootPath);
    File file=new File(rootPath);   
    if(file.isDirectory()&&file.list()!=null)
    {
        System.out.printf("\nThis folder contains %d files/folders\n" ,   file.list().length);
        for(String node:file.list())
        {   
            nodes[i]=new DefaultMutableTreeNode(node);
            System.out.println(" -  "+nodes[i]);
            createTree(node);
            i++;
        }
    }
    else if(file.isFile())
    {   
        nodes[i]=new DefaultMutableTreeNode(rootPath);
        i++;
        return;
    }
    else
        return;
}
4

1 回答 1

1

file.list()仅返回目录的相对名称,因此在将节点传递给下一个递归调用时需要附加父路径:

createTree(rootPath + File.seperator + node);

程序运行的根路径永远不会改变,因此使用相对文件名(目录内部)没有来自根路径的路径将不起作用file = new File(<relative-file-name>)

于 2013-07-12T11:38:40.943 回答