【发布时间】:2021-05-10 17:49:21
【问题描述】:
我最近使用 Fortify 扫描了我们的代码库,我很困惑为什么它会标记某些问题。我面临的一个问题是释放资源。
这里是上下文的 sn-p。
String someLocation = getPathToTheLocation(); //gives location
try (InputStream in = someLocation == null ? Thread.currentThread().getContextClassLoader()
.getResourceAsStream("someFile.xml") : new FileInputStream(new File(someLocation))) {
/// Do Something
}
Fortify 抱怨具有此 try-with-resources 块的方法无法释放由 FileInputStream() 分配的系统资源。 try-with-resources 不是帮我自动关闭 FileInputStream 吗?
假设 Fortify 不识别 try-with-resources 范例,我没有使用它,而是按常规方式进行。
String someLocation = getPathToTheLocation(); //gives location
InputStream in = null;
try {
in = someLocation == null ? Thread.currentThread().getContextClassLoader().getResourceAsStream("someFile.xml")
: new FileInputStream(new File(someLocation));
//Do Something.
} finally {
assert in != null;
try {
in.close();
} catch (IOException ioe) {
throw new IllegalStateException("Could not close input stream.", ioe);
}
}
但它仍然抱怨资源未释放。我无法识别的实际问题可能是什么?
【问题讨论】:
-
Fortify 非常全面,但远非完美。我猜三元运算符会混淆它。也许像
private InputStream open(String location)这样的私有方法不太可能混淆 Fortify。