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.
Join the DZone community and get the full member experience.
Join For FreeYesterday, 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.
Published at DZone with permission of Steven Schwenke. See the original article here.
Opinions expressed by DZone contributors are their own.
Comments