-3

My question is not about null pointer exception. My question is about why while making a file search in C: I got null point exception, even I can list the content. I did a class to search for file. Everything work fine if I'm searching in a directory. But if I search in a drive like c or d, i get a nullpointer exception. How can I fix that ?

here's the code :

import java.io.File;
import java.util.ArrayList;

/**
 * Created by Marcwe on 12/02/2017.
 */
public class FileSearch {

    ArrayList<String> listOfResult = new ArrayList<>(10);

    public FileSearch(File searchPath, String theFile) {
        ArrayList<String> oneList = new ArrayList<>(10);
        listOfResult = searchTheFile(theFile, searchPath, oneList);
        for (String x : listOfResult) {
            System.out.println(x);

        }
    };

    public ArrayList<String> searchTheFile(String theFileToSearch, File inThePath, ArrayList<String> aList) {
        File pathToSearch = inThePath;
        if (!(inThePath == null)) {
            for (File item : pathToSearch.listFiles()) {
                if (!(item == null) && !(item.isFile())) {
                    System.out.println(item.getAbsolutePath());
                    aList = (searchTheFile(theFileToSearch, item, aList));
                } else {
                    if (!(item == null)) {
                        if (item.getName().equalsIgnoreCase(theFileToSearch)) {
                            aList.add(item.getAbsolutePath());
                        }
                    }
                }
            }
        }
        return aList;
    }

    public static void main(String[] args) {
        FileSearch searchTest = new FileSearch(new File("C:/"), "test.txt");
    }
}
Marc We
  • 57
  • 5
  • Tell us more about the error. – byxor Feb 12 '17 at 10:38
  • Possible duplicate of [What is a NullPointerException, and how do I fix it?](http://stackoverflow.com/questions/218384/what-is-a-nullpointerexception-and-how-do-i-fix-it) – Luke Joshua Park Feb 12 '17 at 10:38
  • 2
    You can shorten this code to a couple of lines by using the [appropriate methods from the JDK](https://docs.oracle.com/javase/8/docs/api/java/nio/file/Files.html#walkFileTree-java.nio.file.Path-java.nio.file.FileVisitor-). – Boris the Spider Feb 12 '17 at 10:43

1 Answers1

1
FileSearch searchTest = new FileSearch(new File("C:/"), "test.txt");

Here you browse all the disk to find a file.
It is likely that some folders or files listed by

    for (File item : pathToSearch.listFiles()) {

you invoke in a recursive way cannot be listed with the Java File API.
I think that you could have some issues with virtual or hidden folders.
The Javadoc indicates that it may return null if this abstract pathname (pathToSearch variable here)does not denote a directory, or if an I/O error occurs.
It is rather broad as filesystems may have many particularities and the javadoc cannot reference all them.

Besides you could miss some rights to list some folders or files. Which could rise SecurityException .

Here is Javadoc about return of File[] java.io.File.listFiles():

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. Throws: SecurityException - If a security manager exists and its SecurityManager.checkRead(String) method denies read access to the directory Since: 1.2

So I suppose you should not directly invoke listFiles() in the foreach because a null value would produce a NullPointerException :

for (File item : pathToSearch.listFiles()) {

You should rather invoke listFiles() to retrieve the File array and do the loop only if this is not null :

File[] files = pathToSearch.listFiles();
if (files != null){
  for (File item : files) {
   ...
   }
}

Besides you should catch SecurityException because of potential missing rights on folder or files to avoid unexpected exception at runtime that would prevent the search from finishing.

At last you could reduce the nesting level of the method by applying the fail fast principle : you handle the failing cases as soon as possible.
As you use recursivity, you should do the method very straight readable.

public ArrayList<String> searchTheFile(String theFileToSearch, File inThePath, ArrayList<String> aList) {

    File pathToSearch = inThePath;

    if (inThePath != null)) {

        // fail fast cases
        File[] files = null;
        try {
            files = pathToSearch.listFiles();
        } catch (SecurityException e) {
            return aList;
        }

        if (files == null) {
            return aList;
        }

        // nominal case
        for (File item : files) {
          ...
        }
davidxxx
  • 125,838
  • 23
  • 214
  • 215