gpt4 book ai didi

扫描目录时出现 java.lang.NullPointerException

转载 作者:搜寻专家 更新时间:2023-11-01 03:07:54 25 4
gpt4 key购买 nike

我有一个非常简单的方法来扫描目录结构以执行检查。扫描看起来像这样:

File file = new File(initpath);

for(File hex : file.listFiles(new HexagonNameFilter())) {

for(File wall : hex.listFiles()) {

for(File shelf : wall.listFiles()) {

for(File book : shelf.listFiles()) {

// Perform some actual work
}
}
}
}

该方法在程序执行期间被多次调用。

不一致(意思是,在扫描过程中的某个不可预测的点),我得到一个 java.lang.NullPointerException,堆栈跟踪指向其中一个 for 语句(它也是不一致的)。这没有启发性。我正在考虑将 FilenameFilters 传递给三个 listFiles() 调用,但看不出这对解决问题有何帮助。

最佳答案

您应该验证您是在目录上调用此方法。否则,它返回 null。

listFiles

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.

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.

关于扫描目录时出现 java.lang.NullPointerException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16283488/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com