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

Download Microservices for Java Developers: A hands-on introduction to frameworks and containers. Brought to you in partnership with Red Hat.

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.

Download Modern Java EE Design Patterns: Building Scalable Architecture for Sustainable Enterprise Development.  Brought to you in partnership with Red Hat

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

Published at DZone with permission of Steven Schwenke. See the original article here.

Opinions expressed by DZone contributors are their own.

THE DZONE NEWSLETTER

Dev Resources & Solutions Straight to Your Inbox

Thanks for subscribing!

Awesome! Check your inbox to verify your email so you can start receiving the latest in tech news and resources.

X

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

{{ parent.tldr }}

{{ parent.urlSource.name }}