folder.listFiles() may produce NullPointerException


Posted by Steven

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

  1. File folder = new File("path");
  2. if(folder.listFiles() != null) {
  3. for(File file : folder.listFiles()) {
  4. System.out.println(file.getName());
  5. }
  6. }

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:

  1. File[] files = folder.listFiles();
  2. if(files != null) {
  3. for(File file : files) {
  4. System.out.println(file.getName());
  5. }
  6. }

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. :)

Category: 
Share: