Ploni Almoni
Ploni Almoni

Reputation: 11

File.listFiles throws NullPointer

I'm recursively searching for a file in my computer.

 private static File findFileDepthSearch(File dir, String fileName) {
    File[] files = dir.listFiles();
    for (File f : files) {
        if (f.getName().equalsIgnoreCase(fileName)) {
            return f;
        }
    }
    for (File f : files) {
        if (f.isDirectory()) {
            File res = findFileDepthSearch(f, fileName);
            if(res != null)
            {
                return res;
            }
        }
    }
    return null;
}

After going two levels deep, dir.listFiles returns null. However, this shouldn't be the case because the file in question is in fact a directory. When I try to enter it in the console, it says Acess denied, but according to the javadocs security issues should throw an exception. What am I missing here? Adding this in

if(files==null)
    {
        return null;
    }

fixes the issue, but why is this necessary?

Upvotes: 0

Views: 128

Answers (1)

explv
explv

Reputation: 2759

The documentation states "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs."

If you do not have access to the directory at the file system level, that qualifies as an "I/O error" and so the function will return null.

It only throws a SecurityException if you create a SecurityManager and configure it to restrict access to that directory.

Upvotes: 1

Related Questions