查找错误:" may fail to close stream ",如何解决?



FindBugs将以下代码标记为错误代码。FindBugs表示"此方法可能无法清理(关闭、处置)流、数据库对象或其他需要显式清理操作的资源。"错误标记在output = new FileOutputStream (localFile); 线上

但我们已经将try/finally添加到了块中。

inputStream   input =null;
OutputStream output =null;
try {
    input = zipFile.getInputStream(entry);
    File localFile = new File(unzipFile.getAbsolutePath()
            + File.separator + entryName);
    output = new FileOutputStream (localFile);  // BUG MARKED HERE
    byte[] buffer = new byte[1024 * 8];
    int readLen = 0;
    while ((readLen = input.read(buffer, 0, 1024 * 8)) != -1) {
        output.write(buffer, 0, readLen);
    }
    output.flush();
    output.close();
    input.close();
} finally {
    if(output!=null) {
        output.flush();
        output.close();
    }
    if(input!=null) {
        input.close();
    }
}

删除位于try块中的所有close()调用(以及最后一个flush()调用),因为如果出现错误,将不获取该代码。这就是警告的来源。Findbugs会被触发,以为你试图在try/catch块中处理它们。

此外,在finally中,最好包装另一个try-catch块,这样您就可以处理那里的错误,如果output关闭失败,您仍然可以继续关闭input

                   // your code here
                   output.write(buffer, 0, readLen);
                   // removed these since findbug complains about this
                }
            } finally {
                // TODO some more try catching here so that if output closing 
                // fails you can still try to close second one and log the errors!
                if(output!=null)
                {
                    output.flush();
                    output.close();
                }
                if(input!=null)
                {
                    input.close();
                }
            }

此外,对于java7及以上版本,还有更好的解决方案。看见http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html(感谢@user2864740的链接)。

最新更新