NullPointerException:尝试获取空数组的长度

NullPointerException: Attempt to get length of null array

我正在开发 Android 应用程序。我有以下代码来编写特定文件夹中所有以 XLR 开头的文件的列表:

private List<File> getListFiles(File parentDir) {
    ArrayList<File> inFiles = new ArrayList<File>();
    File[] files = parentDir.listFiles();
    for (File file : files) {
        try {
            if ((file.exists()) && (file != null)) {
                if (file.isDirectory()) {
                    inFiles.addAll(getListFiles(file));
                } else {
                    if (file.getName().startsWith("XLR")) {
                        inFiles.add(file);
                    }
                }
            }


        } catch (Exception e) {
            e.printStackTrace();
        }

    }

    return inFiles;
}

在Android 10和11好像有问题。对于 Android 10,我启用了旧存储,Android 11,我可以访问所有文件。所以问题不在于文件访问。 该文件夹本身可能不在我的应用程序文件夹中,因此需要能够列出文件

我知道这里有一个关于 NPE 的详尽页面,我已尽力遵循那里的建议(我正在检查文件是否存在且不为空),但仍然无济于事。

我觉得可能有一些非常愚蠢的东西,一个更有经验的程序员可能会在 2 秒内挑出...

只要阅读 the documentation 实际的 File 包,这个问题就会很容易解决。

关于方法的文档 File::listFiles:

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.

如您所见,该方法实际上可以 return null 而不仅仅是一个空数组,因此您应该在尝试遍历它之前检查该值是否为空。