0

我有这个方法:

 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();
        }
    }

对于这种方法,声纳给我这个违规:

不好的做法 - 方法可能无法关闭异常流 unZipElementsTo(String, String) 可能无法关闭异常流

但是,我没有看到任何违规行为。也许,这只是一个假阳性?

4

4 回答 4

8

这是正确的。该OutputStream.close()方法本身可以引发异常。如果发生这种情况,例如在您的块的第一行finally{},那么其他流将保持打开状态。

于 2012-09-11T13:09:59.600 回答
2

如果out.close()zf.close()finally块中抛出异常,则不会执行其他关闭。

于 2012-09-11T13:10:00.240 回答
2

或者,如果您使用的是 Java 7 或更高版本,则可以使用新的 try-with-resources 机制,它会为您处理关闭。有关此新机制的详细信息,请参见:http ://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html。

请注意,try-with-resources 也适用于打开和关闭的多个对象,并且仍然保证对象将以与其构造相反的顺序关闭。Quoth同一页面:

请注意,资源的关闭方法以与它们创建相反的顺序被调用。

于 2014-04-03T20:25:32.370 回答
0

为避免在流关闭期间用异常掩盖异常通常建议在 finally 中“隐藏”任何 io 异常。

要修复在 finally 关闭中使用 org.apache.commons.io.IOUtils.closeQuietly(...) 或 guava Closeables.html#closeQuietly(java.io.Closeable)

更多关于异常处理问题: http:
//mestachs.wordpress.com/2012/10/10/through-the-eyes-of-sonar-exception-handling/

于 2013-01-29T08:46:31.363 回答