[英]Why am i getting Possible null pointer dereference in findbug?
On the 5th line of below code spotted as a bug by the findbugs:在 findbugs 发现的错误代码的第 5 行:
Possible null pointer dereference in com.xyz.common.CommonUtils.FolderNotEmpty(String) due to return value of called method [Troubling(13), Normal confidence]由于调用方法的返回值,com.xyz.common.CommonUtils.FolderNotEmpty(String) 中可能的 null 指针取消引用 [Troubling(13),正常置信度]
public static boolean FolderNotEmpty(String path) {
boolean flag = false;
File f = new File(path);
if (f.isDirectory()) {
if (f.listFiles().length > 0) {
flag = true;
LOGGER.info("Folder - " + path + " is not empty.");
} else {
LOGGER.info("Folder - " + path + " is empty.");
}
} else {
LOGGER.warn("The given path is not a directory - " + path);
}
return flag;
}
Because f.listFiles()
can return null
.因为
f.listFiles()
可以返回null
。 Rewrite it with following code:用以下代码重写它:
if (f.listFiles() != null && f.listFiles().length > 0)
You have a race condition:你有一个竞争条件:
f.isDirectory()
, which returns true.f.isDirectory()
,它返回 true。path
with some ordinary file.path
中的目录。f.listFiles()
, which returns null.f.listFiles()
,它返回 null。 To avoid this, say File[] files = f.listFiles();
为避免这种情况,请说
File[] files = f.listFiles();
unconditionally, and then change your if
to if (files != null)
.无条件地,然后将您的
if
更改为if (files != null)
。 Better yet, reduce the nesting in your method this way:更好的是,以这种方式减少方法中的嵌套:
public static boolean folderIsNotEmpty(String path) {
File f = new File(path);
File[] files = f.listFiles();
if (files == null) {
logger.warn("not a directory");
return false;
}
if (files.length > 0) {
logger.info("not empty");
return true;
} else {
logger.info("empty");
return false;
}
}
(Or, if you don't need the log statements, return (files.length > 0)
.) (或者,如果您不需要日志语句,请
return (files.length > 0)
。)
listFiles method of File class can return null.文件 class 的 listFiles 方法可以返回 null。 So you need to check if f.listFiles() return null at 5th line, otherwise, if (f.listFiles().length > 0) can cause NPE.
所以你需要检查 f.listFiles() 是否在第 5 行返回 null,否则,如果 (f.listFiles().length > 0) 会导致 NPE。
Actually, your code is perfectly safe.实际上,您的代码是完全安全的。
If this abstract pathname does not denote a directory, then this method returns null.
如果此抽象路径名不表示目录,则此方法返回 null。 Otherwise an array of File objects is returned, one for each file or directory in the directory.
否则返回一个 File 对象数组,一个对应于目录中的每个文件或目录。
That is exactly what you have covered.这正是你所涵盖的。
However, Findbugs cannot know about that contract.但是,Findbugs 无法知道该合同。 It just says there is a potential NPE.
它只是说存在潜在的NPE。 You can choose to ignore that.
你可以选择忽略它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.