Over a million developers have joined DZone.

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()) {

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) {

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 Building Reactive Microservices in Java: Asynchronous and Event-Based Application Design. Brought to you in partnership with Red Hat

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 }}