Peter Szabo Peter Szabo - 1 year ago 162
Java Question

File.isDirectory and isFile both false

I'm writing a java application, that lists directory contents.
When it comes to list the directory, the behavior of .isDirectory() method returns false for items, I'm pretty sure are directories.

public List<DefaultMutableTreeNode> getNodes(String path)
{
List<DefaultMutableTreeNode> nodes = new ArrayList<>();

File directory = new File(path).getAbsoluteFile();
File[] contents = directory.listFiles();

for (File item : contents)
{
if (item.isDirectory())
{
DefaultMutableTreeNode node = new DefaultMutableTreeNode(item.getName());
node.add(new DefaultMutableTreeNode("Placeholder..."));
nodes.add(node);
}
else
{
nodes.add(new DefaultMutableTreeNode(item.getName()));
}
}

return nodes;
}


The above code always runs to the else branch.
If I replace the loop, I get an even weirder result:

for (File item : contents)
{
System.out.printf("%s - directory? %b file? %b %n", item.getAbsoluteFile().getPath(), item.isDirectory(), item.isFile());
}


The output of this is:

/storage/other - directory? false file? false

/storage/games - directory? false file? false

/storage/apps - directory? false file? false

/storage/testfile - directory? false file? false


if I list the files in the /storage directory, it is clear as day, that all but testfile is a directory.

What am I doing wrong?




To avoid confusion, /storage is an actual directory in /. Not a typo.

Answer Source

The cause of the problem was badly configured access permissions.
isDirectory, isFile, and exists will return false, if the user running the application doesn't have execute permissions.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download