[英]File.listFiles throws NullPointer
I'm recursively searching for a file in my computer. 我在计算机中递归搜索文件。
private static File findFileDepthSearch(File dir, String fileName) {
File[] files = dir.listFiles();
for (File f : files) {
if (f.getName().equalsIgnoreCase(fileName)) {
return f;
}
}
for (File f : files) {
if (f.isDirectory()) {
File res = findFileDepthSearch(f, fileName);
if(res != null)
{
return res;
}
}
}
return null;
}
After going two levels deep, dir.listFiles
returns null
. 深入两个级别之后,
dir.listFiles
返回null
。 However, this shouldn't be the case because the file in question is in fact a directory. 但是,事实并非如此,因为相关文件实际上是目录。 When I try to enter it in the console, it says Acess denied , but according to the javadocs security issues should throw an exception.
当我尝试在控制台中输入它时,它说Acess否认 ,但是根据javadocs,安全性问题应该引发异常。 What am I missing here?
我在这里想念什么? Adding this in
在此添加
if(files==null)
{
return null;
}
fixes the issue, but why is this necessary? 解决了这个问题,但是为什么这是必要的呢?
The documentation states "Returns null if this abstract pathname does not denote a directory, or if an I/O error occurs." 文档指出“如果此抽象路径名不表示目录,或者发生I / O错误,则返回null。”
If you do not have access to the directory at the file system level, that qualifies as an "I/O error" and so the function will return null
. 如果您无权访问文件系统级别的目录,则将其视为“ I / O错误”,因此该函数将返回
null
。
It only throws a SecurityException
if you create a SecurityManager
and configure it to restrict access to that directory. 仅当您创建
SecurityManager
并将其配置为限制对该目录的访问时,它才会引发SecurityException
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.