Question: I am using this code to search for a specific file pattern recursively in a given directory:

```
if (file.isDirectory()) {
        System.out.println("Searching directory ... "
                + file.getAbsoluteFile());
        if (file.canRead()) {
            System.out.println("Can read...");
            if (file.listFiles() == null) {
                System.out.println("yes it is null");
            }
            for (File temp : file.listFiles()) { // Problemetic line
                if (temp.isDirectory()) {
                    search(temp);
                } else {
                    // code to find a file
                }
            }
}

```

Above code outputs me like this (also I get exception):

```
Searching directory ... C:\swsetup\SP46840\Lang\zh-TW
Can read...
Searching directory ... C:\System Volume Information
Can read...
yes it is null

```

Exception is:

```
Exception in thread "main" java.lang.NullPointerException
at Demo.search(Demo.java:61)
at Demo.search(Demo.java:63)

```

In my code the line is pointing to : `(file.listFiles())`, because it is trying to get list of files from system directories like "System Volume Information". I assume because it's a system directory, so some problem maybe happening which I am not aware.

My question is:

* How to handle this scenario, so that even `NullPointerException` occurs my `foreach` loop continues?
* Or better how to avoid exception in first place (like by checking if it is a system directory etc)?

Can anyone please guide me in this? Note: This is happening in Windows XP (I have tested earlier in Windows 7 few months back but I assume issue was not occurring there)

Answer: 
Try this:

```
if (file.isDirectory()) {
        System.out.println("Searching directory ... "
                + file.getAbsoluteFile());
        if (file.canRead()) {
            System.out.println("Can read...");
            if (file.listFiles() == null) {
                System.out.println("yes it is null");
            } else { /* add the else */
              for (File temp : file.listFiles()) { // Problemetic line
                  if (temp.isDirectory()) {
                      search(temp);
                  } else {
                      // code to find a file
                  }
              }
            }
}

```
from javaDoc:

> 
> 
> ```
>  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 <code>null</code> if this abstract pathname
>  does not denote a directory, or if an I/O error occurs.
> 
> ```
> 
> 

So it's good idea to check null and use approach from Narendra Pathai's anwser