Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

IntelliJ "may cause NullPointerException" warning when using File.listFiles()

This is the most minimal example that still generates the warning:

File searchpath = new File(path);
for(File file: searchpath.listFiles()){ ... }

(path is a string passed into this method)

The second line, with the for loop, triggers an IDE warning:

Dereference of searchPath.listFiles() may produce 'java.lang.NullPointerException'

Given that I just initialized the variable, and that my program works, my first instinct is that this is a crap warning.

Is this a valid warning, and if so, how do I clear it?

*edit1

File, per its Javadoc, will throw a NPE if you give it a null path. So, clearing the error seems like it would be a case of annotating the path argument so that it's known to never be null.

like image 949
Mikey T.K. Avatar asked May 11 '16 01:05

Mikey T.K.


2 Answers

The reason for the warning is that listFiles() will return null under certain conditions. According to the documentation, it will return null if path does not refer to a directory, or if an I/O error occurs while accessing it. To guard against that possibility, and to eliminate the warning, you can do this:

File searchpath = new File(path);
File[] files = searchpath.listFiles();
if(files == null){
    // handle path not a directory, or other error
} else {
    for(File file: files){ ... }
}

Refer to https://docs.oracle.com/javase/7/docs/api/java/io/File.html#listFiles()

like image 162
Hank D Avatar answered Oct 08 '22 07:10

Hank D


Whenever IntelliJ throws something like that at me, I just usually find it in my best interests to but it in a try-catch block.

Of course, if you're ABSOLUTELY sure that it will never fail, then there might not be a point, but I consider it good practice to always account for all possible errors, since that's our job as programmers.

like image 24
a.deshpande012 Avatar answered Oct 08 '22 08:10

a.deshpande012