Java.lang.NullPointerException when scanning directories

I have a very simple method that scans the directory structure to perform validation. Scanning is as follows:

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 many times during program execution.

Directly (which means at some unpredictable point in the scanning process), I get a java.lang.NullPointerException with a stack trace pointing to one of the for statements (which one is also inconsistent). This is not instructive. I was thinking of passing FilenameFilters into three calls to listFiles (), but I can't figure out how this would help.

+4
source share
1 answer

You must make sure that you call this method in the directory. Otherwise, it returns null.

listFiles

public file [] listFiles ()

Returns an array of abstract paths denoting files in the directory indicated by this abstract path name.

If this abstract path name does not indicate a directory, then this method returns null . Otherwise, an array of File objects is returned, one for each file or directory in the directory. Path names that denote the directory itself and the parent directory of the directory are not included in the result. Each resulting abstract path is built from this abstract path using a file (file, line) constructor. Therefore, if this path is absolute, then each result pathname is absolute; if this path is relative, then each resulting path name will refer to the same directory.

There is no guarantee that name strings in the resulting array will appear in any particular order; they are not, in particular, guaranteed to appear in alphabetical order.

Returns: an array of abstract paths denoting files and directories in the directory indicated by this abstract empty name. the array will be empty if the directory is empty. Returns null if this abstract path name does not indicate a directory, or if an I / O error occurs.

+3
source

All Articles