如何在Java中找到未关闭的I / O资源? [英] How to find unclosed I/O resources in Java?

查看:731
本文介绍了如何在Java中找到未关闭的I / O资源?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

如上所述此处。

如何在我的项目中搜索未关闭此类资源的地方,例如这种错误:

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
}

我尝试了一些静态分析工具,如PMD和FindBugs,但他们没有将上面的代码标记为错误。

I've tried some static analysis tools such as PMD and FindBugs, but they don't flag the above code as being wrong.

推荐答案

如果具有修改规则的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.

运行它就像这样简单:

%>jvisualvm

选择正在运行的流程。选择选项保存堆转储(或者那种效果),打开堆转储并在浏览器中查看文件流的类实例,或查询它们。

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中找到未关闭的I / O资源?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆