java - FindBugs :"may fail to close stream ",如何解决?

标签 java stream findbugs

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

但是我们已经在 block 中添加了 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 block 中的所有 close() 调用(以及最后一个 flush() 调用),因为该代码将无法访问以防出错。这就是警告的来源。在那里触发 Findbugs 以相信您试图在 try/catch block 中处理它们。

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

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

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

关于java - FindBugs :"may fail to close stream ",如何解决?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20628232/

相关文章:

java - 将 BufferedImage 保存为 TIFF 文件?

JavaFX FileChooser 选择文件和/或目录?

java - 如何从 ListView 中完全编辑/删除元素?

javascript - 如何从nodejs服务器流式传输到客户端

java - 选择更有利可图的流结果

java - 如何修复 Android 应用程序在 Flask 服务器上上传文件时的 400 错误

c - 抽象流 C

java - 是否有 Sonar、Findbugs 或 PMD 规则来检测 CodePro 检测到的这种可能的 NPE?

android - FindBugs Android Gradle No classes configured 错误

android - Findbugs 失败并显示 "java.io.IOException: No files to analyze could be opened"