Skip to Main Content

Java Programming

Announcement

For appeals, questions and feedback about Oracle Forums, please email oracle-forums-moderators_us@oracle.com. Technical questions should be asked in the appropriate category. Thank you!

I get a strange NullPointerException when using a recursive method

807589Dec 26 2008 — edited Dec 26 2008
I found a code snippet that uses a recursive method for searhing files in folders and subfolders, but I get a NullPointerException when the path is set to "C:\\Users\\Roxxor\\Documents", but it works if the path is set to "C:\\Users\\Roxxor\\Documents\\Java".

Why this extremly strange behaviour?

import javax.swing.*;

import javax.swing.tree.*;

import java.io.*;



public class DIC extends JFrame{

        public DIC() {

                DefaultMutableTreeNode master = new DefaultMutableTreeNode("Node Title");

                JTree tree = new JTree(master);

                JScrollPane scroll = new JScrollPane(tree);

                this.setSize(200,400);

                this.getContentPane().add(scroll);

                // pass the directory that you wish to list the contents

                listAllFiles("C:\\Users\\Roxxor\\Documents\\Java",  master, true);         // Works
               // listAllFiles("C:\\Users\\Roxxor\\Documents",  master, true);         // Throws an exception

                setVisible(true);
                pack();

        }



        /*

        * @params: String directory ~ the directory to scan

        * @params: DefaultMutableTreeNode parent ~ the node to add any files as children

        * @params: Boolean recursive ~ determine whether to scan all subdirectories, or just the parent

        */

        public static void listAllFiles(String directory, DefaultMutableTreeNode parent, Boolean recursive) {

                File [] children = new File(directory).listFiles(); // list all the files in the directory

                for (int i = 0; i < children.length; i++) { // loop through each

                        DefaultMutableTreeNode node = new DefaultMutableTreeNode(children.getName());

// only display the node if it isn't a folder, and if this is a recursive call

if (children[i].isDirectory() && recursive) {

parent.add(node); // add as a child node
listAllFiles(children[i].getPath(), node, true); // call again for the subdirectory

} else if (!children[i].isDirectory()){ // otherwise, if it isn't a directory

parent.add(node); // add it as a node and do nothing else

}

}


}
public static void main(String[] args)
{
new DIC();
}

}
Comments
Locked Post
New comments cannot be posted to this locked post.
Post Details
Locked on Jan 23 2009
Added on Dec 26 2008
4 comments
530 views