java 强化安全问题“未发布的资源流”
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/42270898/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Fortify security issue "Unreleased resource stream"
提问by purushothaman
I am getting a fortify finding for "Unreleased resource stream" on the code below.
我在下面的代码中得到了“未发布的资源流”的强化发现。
Resource[] l_objResource = resourceLoader.getResources(configErrorCode);
Properties l_objProperty = null;
for (int i = 0; i < l_objResource.length; i++) {
l_objProperty = new Properties();
l_objProperty.load(l_objResource[i].getInputStream());
}
The function loadErrorCode()
in BaseErrorParser.java
sometimes fails to release a system resource allocated by getInputStream();
该函数loadErrorCode()
中BaseErrorParser.java
有时无法释放被分配的系统资源getInputStream();
Can anyone explain the finding or help fix the issue?
任何人都可以解释这一发现或帮助解决问题吗?
From the comment below, but the context is not clear (JW):
从下面的评论,但上下文不清楚(JW):
ObjectInputStream l_objObjInputStream = null;
Map l_mapRet = null;
try {
l_objObjInputStream = new ObjectInputStream(new FileInputStream(p_objFilename));
Object l_objTemp = l_objObjInputStream.readObject();
l_mapRet = (Map) l_objTemp;
} finally {
if (l_objObjInputStream != null) {
l_objObjInputStream.close();
}
}
回答by Sravya
You are not closing the input stream which is opened by below line of code
您没有关闭由以下代码行打开的输入流
l_objResource[i].getInputStream();
Usually fortify scanner reports Unreleased resource stream issue if there are any input or out streams which are opened but not closed after their usage. The ideal way to deal with these issues is to close all the opened streams in finally block so that even during exception scenarios they won't create any issues.
如果有任何输入或输出流在使用后打开但未关闭,通常强化扫描程序会报告未释放的资源流问题。处理这些问题的理想方法是关闭 finally 块中所有打开的流,这样即使在异常情况下也不会产生任何问题。
You can have a try - finally block around the code and close the stream as below.
您可以尝试一下 - 最后阻止代码并关闭流,如下所示。
Resource[] l_objResource = resourceLoader.getResources(configErrorCode);
Properties l_objProperty = null;
InputStream is = null;
for (int i = 0; i < l_objResource.length; i++) {
l_objProperty = new Properties();
try {
is = l_objResource[i].getInputStream();
l_objProperty.load(is);
} finally {
if(is!=null) {
is.close();
}
}
}
Please check if it works in your case.
请检查它是否适用于您的情况。
回答by vrushabh boharpi
You can use Try with resource here. This will automatically close your stream.
您可以在此处将 Try 与资源一起使用。这将自动关闭您的流。
Map l_mapRet = null;
try (ObjectInputStream l_objObjInputStream = new ObjectInputStream(new FileInputStream(p_objFilename))){
Object l_objTemp = l_objObjInputStream.readObject();
l_mapRet = (Map) l_objTemp;
} Catch(IOException E){
// Handle exception
}