How to find unclosed I/O resources in Java?

北城以北 提交于 2019-12-03 15:39:19

问题


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.


回答1:


It's probably matter of setting - I ran FindBugs through my IDE plugin and it reported OS_OPEN_STREAM.




回答2:


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:

%>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.




回答3:


In Java 7, they added a feature of using closable resources in current scope (so called try-with-resources), such as:

public void someMethod() {
    try(InputStream is = new FileInputStream(file)) {
        //do something here
    } // the stream is closed here
}

In older versions, the common technique is using try-catch-finally chain.



来源:https://stackoverflow.com/questions/7343158/how-to-find-unclosed-i-o-resources-in-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!