import java.io.*;class FileDemo {
public static void main(String[] args)  {
File dir = new File("c:\\");
showDir(dir);

}

public static void showDir(File dir)  { File[] files = dir.listFiles();
for(int x = 0 ; x < files.length ; x++) {
if(files[x].isDirectory()) {
showDir(files[x]);
}
else
System.out.println(files[x]);
}
}
}为何报空指针啊,代码我是照着教程打的,教程并没有报错呢。

解决方案 »

  1.   

    [img=https://img-bbs.csdn.net/upload/201709/08/1504881407_633808.jpg][/img
    目录换成C:\Program Files后如图显示,没有直接报错,但还是报错了。
    换成子目录比较少的目录后,不报错。
      

  2.   

    public File[] listFiles()
    Returns an array of abstract pathnames denoting the files in the directory denoted by this abstract pathname.
    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.There is no guarantee that the name strings in the resulting array will appear in any specific order; they are not, in particular, guaranteed to appear in alphabetical order.Note that the Files class defines the newDirectoryStream method to open a directory and iterate over the names of the files in the directory. This may use less resources when working with very large directories.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这是API里面的说明
      

  3.   

    你得对files 判断是否为空
      

  4.   


    import java.io.*;class FileDemo {
    public static void main(String[] args) {
    File dir = new File("c:\\");
    showDir(dir); } public static void showDir(File dir) { File[] files = dir.listFiles();
    // System.out.println(files == null);
    if (files != null) {
    for (int x = 0; x < files.length; x++) { if (files[x].isDirectory())
    showDir(files[x]); else
    System.out.println(files[x]); }
    } }
    }
    问题解决了,但为什么有时候files会返回空呢,我测试过传空目录进去也没有返回null。
      

  5.   

    Windows 系统有很多目录是链接,指向另外一个目录,或者没有权限访问的,你自己创建一个去看看就知道了没问题。