NullPointerException when using java.io.File

这一生的挚爱 提交于 2019-12-29 01:53:12

问题


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 ++;
                }
            }
        }
    }
}

回答1:


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)




回答2:


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.




回答3:


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.




回答4:


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



来源:https://stackoverflow.com/questions/11643011/nullpointerexception-when-using-java-io-file

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!