最近的一个项目中,使用Converity检测代码时,检测到了到了一些资源泄露问题。大概就是下面这个样子代码,检测中提到inputStream未关闭。但是我看到好多代码都是未关闭inputStream(zipFile.getInputStream(xmlEntry))这个流,所以有些疑惑,到底应不应该手动关闭这个流。
1、代码
ZipFile zipFile = null;
InputStream inputStream = null;
try{
zipFile = new ZipFile(path);
ZipArchiveEntry xmlEntry = zipFile.getEntry("des.xml");
inputStream = zipFile.getInputStream(xmlEntry);
.......
}catch(Exception e){
}finally{
zipFile.close();
}
......
2、我的疑惑
我在finally代码块中执行了zipFile.close(),inputStream这个流还需要手动关闭吗?
如果不确定最好是关闭吧 , 如果ZipFile里面已经处理过相关流的关闭,那就不用了。
另外 你可以在zipfile 被close后,debug或者打印 下 inputstream的是否已经关闭,养成自己探索和判断的好习惯哦!
比如你家有两道防盗门,你都开了然后出门的时候只关了一个,你觉得合适吗
不用了 你看下zipFile.close()方法 执行其他从zipFile获取的流都关闭了; zipFile.close()方法上面有注释写了 “
<p> Closing this ZIP file will close all of the input streams * previously returned by invocations of the {@link #getInputStream * getInputStream} method.
”