Java NullPointerException when calling listFiles()

2020-03-01 07:49发布

问题:

I have a series of folders containing books on a server which I am accessing with this piece of code. I want to make each of these folders an object so I can do some work with the files inside them later on. I'm trying to use this method to return a list of the folders as Book objects.

public List<Book> getBooks(File folder){
    List<Book> books = new ArrayList<Book>();
    for (File f : folder.listFiles()){
        if (f.isDirectory()){
            System.out.println(f.getAbsolutePath() + "" + f.listFiles());
            books.add(new Book(f));
        }
    }
    return books;
}

The println statement in this block is printing, as it should, the direct path to the folder and then the memory address along with some other information. However, somewhere in the folder it is printing out null when listFiles() is called. The folder that it is doing this on is not empty. This supposedly empty folder is then passed to my class init method.

public Book(File bookFolder) {
    this.bookFolder = bookFolder;
    this.bookPath = bookFolder.getAbsolutePath();

    System.out.println(bookFolder + " " + bookFolder.listFiles());

    for (File f : bookFolder.listFiles()) {
        ...
    }
}

The println statement in this block prints out the exact same path to the folder and then a different memory address, which is also expected. When it hits the "empty" folder it prints null for the memory address again.

Now, for the real issue, the line with the for loop is where the program crashes and throws a NullPointerException which isn't even described in the documentation for the listFiles method.

Why could this be happening? Also, why are my non-empty folders returning null?

回答1:

The documentation for the listFiles() method clearly states that it "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs."

One of the most common reasons that a directory cannot be listed is that the process lacks the right permissions. Are you running this as yourself, or in some sort of service that runs as a different user?

By the way, the File API is a great example of how bad life can be without exceptions.



回答2:

I had a similar problem with dir.listfiles(); returning null for the user folder \AppData\Local\Microsoft\Windows\Temporary Internet Files\Content.IE5\

it was the folder had by default Permissions set on "everyone" Deny all

what screwed me over i think was the fact that I never expected any Deny permission to exist there.

also for any one thats unclear on what i mean by a deny permission

when you set deny for user permissions it overrides the allow for user permissions unless you remove it and it was on a default install of windows 10 home.