Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

folder.listFiles() May Produce NullPointerException [Snippet]

DZone's Guide to

folder.listFiles() May Produce NullPointerException [Snippet]

If you're calling folder.listFiles() more than once in your code, you might be getting the dreaded NullPointerException. Be sure you only run it once.

· Java Zone ·
Free Resource

Start coding something amazing with our library of open source Cloud code patterns. Content provided by IBM.

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.

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.

Code something amazing with the IBM library of open source blockchain patterns.  Content provided by IBM.

Topics:
java ,nullpointerexception ,intellij idea ,folder.listfiles

Published at DZone with permission of

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}