简体   繁体   中英

NullPointerException when using java.io.File

I am trying to use this program to count all the files in the D:\\ drive but it is throwing an exception when I run it.

package lmh;

import java.io.File;

public class FileList {

    static int fileNum = 0;
    static int directoryNum = 0;
    static int cannotRead = 0;

    public static void main(String[] args) {
        File f = new File("e:/");
        printFileStructure(f);
        System.out.println("result:");
        System.out.println("file number:" + fileNum);
        System.out.println("directory number:" + directoryNum);
        System.out.println("cannot rend:" + cannotRead);
    }

    public static void printFileStructure(File f) {
        File[] files = f.listFiles();
        for (int i = 0; i < files.length; i++) {
            if (files[i].isFile()) {
                if (files[i].canRead()) {
                    fileNum++;
                    System.out.println(files[i].getName());
                } else {
                    cannotRead ++;
                } 
            }
            else if (files[i].isDirectory()) {
                if (files[i].canRead()) {
                    directoryNum++;
                    printFileStructure(files[i]);
                } else {
                    cannotRead ++;
                }
            }
        }
    }
}

File.listFiles() is not guaranteed to return a non-null value. This tends to occur (from my experience) because Java could see what looked like directory, but could not list it (Junctions come to mind)

Even the javadoc of

f.listFiles()

says... 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.

So i believe this is the culprit.

For the reason that MadProgrammer pointed out, add a null-check.

Replace:

for (int i = 0; i < files.length; i++) {

with

if(files != null)
    for (int i = 0; i < files.length; i++) {

I changed the drive to D (as I have no E drive) and the program completed successfully on my machine with this fix.

try "E:\\\\" for getting into the directory. I think it should work.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM