Java中如何查找未关闭的I/O资源?
Java 中的许多 I/O 资源(例如 InputStream 和 OutputStream)在使用完毕后需要关闭,如所讨论的 此处。
我如何在我的项目中搜索此类资源未关闭的地方,例如这种错误:
private void readFile(File file) throws IOException {
InputStream in = new FileInputStream(file);
int nextByte = in.read();
while (nextByte != -1) {
// Do something with the byte here
// ...
// Read the next byte
nextByte = in.read();
}
// Oops! Not closing the InputStream
}
我尝试了一些静态分析工具,例如PMD和FindBugs,但它们没有将上述代码标记为错误。
Many I/O resources in Java such as InputStream and OutputStream need to be closed when they are finished with, as discussed here.
How can I search my project for places where such resources are not being closed, e.g. this kind of error:
private void readFile(File file) throws IOException {
InputStream in = new FileInputStream(file);
int nextByte = in.read();
while (nextByte != -1) {
// Do something with the byte here
// ...
// Read the next byte
nextByte = in.read();
}
// Oops! Not closing the InputStream
}
I've tried some static analysis tools such as PMD and FindBugs, but they don't flag the above code as being wrong.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这可能是设置的问题 - 我通过 IDE 插件运行 FindBugs,它报告了 OS_OPEN_STREAM。
It's probably matter of setting - I ran FindBugs through my IDE plugin and it reported OS_OPEN_STREAM.
如果修改规则的 FindBugs 不适合您,另一种较慢的方法是堆分析。 VisualVM 允许您使用 OQL 查询堆转储中在任何给定时间打开的特定类型的所有对象。然后,您可以检查打开到程序中此时不应访问的文件的流。
运行它非常简单:
选择正在运行的进程。选择选项保存堆转储(或类似效果),打开堆转储并在浏览器中查看文件流的类实例,或查询它们。
If FindBugs with modified rules doesn't work for you, another slower approach is heap analysis. VisualVM allows you to query all objects of a specific type that are open at any given time within a heap dump using OQL. You could then check for streams open to files that shouldn't be accessed at that point in the program.
Running it is as simple as:
Choose the running process. Choose option save heap dump (or something to that effect), open the heap dump and look at class instances for file streams in the browser, or query for them.
在Java 7中,他们添加了在当前范围内使用可关闭资源的功能(所谓的try-with-resources),例如:
在旧版本中,常见的技术是使用try-catch-finally链。
In Java 7, they added a feature of using closable resources in current scope (so called try-with-resources), such as:
In older versions, the common technique is using try-catch-finally chain.