java – FindBugs:“可能无法关闭流”,如何解决?
内容导读
互联网集市收集整理的这篇技术教程文章主要介绍了java – FindBugs:“可能无法关闭流”,如何解决?,小编现在分享给大家,供广大互联网技能从业者学习和参考。文章包含1481字,纯文字阅读大概需要3分钟。
内容图文
![java – FindBugs:“可能无法关闭流”,如何解决?](/upload/InfoBanner/zyjiaocheng/817/7a871b5354e14cc693d7ab4a02dfd364.jpg)
以下代码被FindBugs标记为错误.
FindBugs说“这种方法可能无法清理(关闭,处理)流,数据库对象或需要显式清理操作的其他资源.”
错误标记在输出行= 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块中处理它们.
另外在最后你最好包装另一个try catch块,以便你可以处理那里的错误,如果输出结束失败,你仍然可以继续关闭输入.
// 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:“可能无法关闭流”,如何解决?全部内容,希望文章能够帮你解决java – FindBugs:“可能无法关闭流”,如何解决?所遇到的程序开发问题。 如果觉得互联网集市技术教程内容还不错,欢迎将互联网集市网站推荐给程序员好友。
内容备注
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 gblab@vip.qq.com 举报,一经查实,本站将立刻删除。
内容手机端
扫描二维码推送至手机访问。