Reputation: 503
I have a very simple method that scans a directory structure to perform a check. The scanning looking like this:
File file = new File(initpath);
for(File hex : file.listFiles(new HexagonNameFilter())) {
for(File wall : hex.listFiles()) {
for(File shelf : wall.listFiles()) {
for(File book : shelf.listFiles()) {
// Perform some actual work
}
}
}
}
The method is called lots of times during the execution of the program.
Inconsistently (meaning, at some unpredictable point in the scanning process), I get a java.lang.NullPointerException with the stack trace pointing at one of the for statements (which one it is is also inconsistent). This is not enlightening. I was thinking of passing FilenameFilters to the three listFiles() calls, but can't see how that would help the issue.
Upvotes: 4
Views: 1062
Reputation: 393811
You should verify that you are calling this method on a directory. Otherwise, it returns null.
listFiles
public File[] listFiles()
Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
If this abstract pathname does not denote a directory, then this method returns null. Otherwise an array of File objects is returned, one for each file or directory in the directory. Pathnames denoting the directory itself and the directory's parent directory are not included in the result. Each resulting abstract pathname is constructed from this abstract pathname using the File(File, String) constructor. Therefore if this pathname is absolute then each resulting pathname is absolute; if this pathname is relative then each resulting pathname will be relative to the same directory.
There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.
Returns: An array of abstract pathnames denoting the files and directories in the directory denoted by this abstract pathname. The array will be empty if the directory is empty. Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs.
Upvotes: 3