Mastodon

Folder.listfiles() may produce nullpointerexception

Yesterday, I noticed a strange warning during a code review. IntelliJ IDEA warned me about this code:

File folder = new File("path");
if(folder.listFiles() != null) {
    for(File file : folder.listFiles()) {
        System.out.println(file.getName());
    }
}

The warning said “Dereference of ‘folder.listFiles()’ may produce ‘java.lang.NullPointerException’”. I wondered why because there is an explicit NPE-check in line 2. Then I realized that this check is pointless. listFiles() will search the given directory for files at every call. So by having two calls in the code above, the directory could be empty when the second call executes, even when it was not at the time the first call hits. (Also, listFiles() will return null if the given path is not a directory.)

Here’s a better solution:

File[] files = folder.listFiles();
if(files != null) {
    for(File file : files) {
        System.out.println(file.getName());
    }
}

Now, the method listFiles() is only called once, so the folder cannot be emptied between two calls.

Yeah, this is an easy one - but maybe you wondered about this warning as I did. :)