FindBugs:"可能无法关闭流",如何解决?

sma*_*art 5 java findbugs 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();
    }
}
Run Code Online (Sandbox Code Playgroud)

hcp*_*cpl 7

删除位于块中的所有close()调用(以及最后一次flush()调用),try因为如果出现错误,将无法访问该代码.这就是警告的来源.在那里触发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();
                }
            }
Run Code Online (Sandbox Code Playgroud)

对于java 7及更高版本,还有更好的解决方案.请参阅http://docs.oracle.com/javase/tutorial/essential/exceptions/tryResourceClose.html(感谢@ user2864740获取该链接).