Tell me more ×
Stack Overflow is a question and answer site for professional and enthusiast programmers. It's 100% free, no registration required.

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;
}
share|improve this question
The recursion is called, but where do you put all the created sub-trees together? – DaDaDom yesterday

1 Answer

up vote 1 down vote accepted

file.list() returns only the relative names of the directory so you need to append the parent path when passing the node to the next recursive call :

createTree(rootPath + File.seperator + node);

The root path where your program runs never changes so using relative file name (inside directories) without the path from the root path will not work for file = new File(<relative-file-name>)

share|improve this answer
1  
thanks a lot....worked perfectly. I would also like to know if it is a good approach to make a tree recursively? – Saurabh Goyal yesterday
For that I will need to see more code, like where nodes and rootNode are declared. note that you override rootNode on every recursive call so at the end it will point to the last deepest file in your directory hierarchy – giorashc yesterday

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.