Sonar violation: quot;Method may fail to close stream on exceptionquot;(声纳违规:“方法可能无法在异常时关闭流)
问题描述
我有这个方法:
private void unZipElementsTo(String inputZipFileName, String destPath) throws FileNotFoundException, IOException {
OutputStream out = null;
InputStream in = null;
ZipFile zf = null;
try {
zf = new ZipFile(inputZipFileName);
for (Enumeration<? extends ZipEntry> em = zf.entries(); em.hasMoreElements();) {
ZipEntry entry = em.nextElement();
String targetFile = destPath + FILE_SEPARATOR + entry.toString().replace("/", FILE_SEPARATOR);
File temp = new File(targetFile);
if (!temp.getParentFile().exists()) {
temp.getParentFile().mkdirs();
}
in = zf.getInputStream(entry);
out = new FileOutputStream(targetFile);
byte[] buf = new byte[4096];
int len;
while ((len = in.read(buf)) > 0) {
out.write(buf, 0, len);
}
out.flush();
out.close();
in.close();
}
}
finally
{
if (out!=null) out.close();
if (zf!=null) zf.close();
if (in!=null) in.close();
}
}
对于这个方法,Sonar 给我这个违规:
For this method Sonar give me this Violation:
不好的做法 - 方法可能无法在异常时关闭流unZipElementsTo(String, String) 可能无法在异常时关闭流
Bad practice - Method may fail to close stream on exception unZipElementsTo(String, String) may fail to close stream on exception
但是,我没有看到任何违规行为.也许,它只是一个假阳性?
But, I don't see any violations there. Maybe, it is just a False-positive ?
推荐答案
没错.OutputStream.close()
方法本身可以抛出异常.如果发生这种情况,例如在 finally{}
块的第一行,其他流将保持打开状态.
That's right.
The OutputStream.close()
method can itself throw an exception.
If this happens, e.g. on the 1st line of your finally{}
block, then the other streams will be left open.
这篇关于声纳违规:“方法可能无法在异常时关闭流"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:声纳违规:“方法可能无法在异常时关闭流"


基础教程推荐
- Java 实例变量在两个语句中声明和初始化 2022-01-01
- 如何在 Spring @Value 注解中正确指定默认值? 2022-01-01
- 不推荐使用 Api 注释的描述 2022-01-01
- Java Swing计时器未清除 2022-01-01
- 大摇大摆的枚举 2022-01-01
- 验证是否调用了所有 getter 方法 2022-01-01
- 从 python 访问 JVM 2022-01-01
- 如何在 JFrame 中覆盖 windowsClosing 事件 2022-01-01
- 多个组件的复杂布局 2022-01-01
- 在 Java 中创建日期的正确方法是什么? 2022-01-01