My task is to show a tree of all directories/files of a PC drive,
I have a class DirectoryNode that extends DefaultMutableTreeNode with File field directoryPath. I build nodes recursively:
public void buildDirectoryTree(){
if(!directoryPath.isDirectory()){
return;
}
for(File f : directoryPath.listFiles()){
if(f.isHidden() || !f.exists()) continue;
DirectoryNode newChild = new DirectoryNode(f);
add(newChild);
newChild.buildDirectoryTree();
}
}
It works fine for concrete directories, but when I try to use it for whole drive, or some large directories, JTree with this node does not show up at all
I think it encounters a problem with specific directories. I've add exists and is Hidden checks to skip this problem roots, but it didn't help.
In addition, exists, isHidden and isDirectory return false for some of my valid directories directories (I am using Windows 10).
File.listFiles()is one of those ancient methods that violates Java's convention/good practice to never returnnullfrom a method that returns an array. So you have to check fornull.From the docs:
I have changed your code to make it a little safer. If it's called from the EDT, you might want to add some log message or the like instead of throwing the exception into nirvana.
As others have pointed out, there are more modern APIs and they have been introduced for good reasons. I recommend to read up on NIO2 and the
PathAPIs for better solutions.