Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to find unclosed I/O resources in Java?

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.

like image 534
Andrew Swan Avatar asked Sep 08 '11 04:09

Andrew Swan


People also ask

What is I o stream in Java?

An I/O Stream represents an input source or an output destination. A stream can represent many different kinds of sources and destinations, including disk files, devices, other programs, and memory arrays.

What will happen if you forget to close the stream of the i/o file?

Bad things that can happen when you don't close your streams: you can run out of file handles. data that you think is written to disk may still be in the buffer (only) files might still be locked for other processes (depends on the platform)

What is InputStream and OutputStream in Java?

In Java, streams are the sequence of data that are read from the source and written to the destination. An input stream is used to read data from the source. And, an output stream is used to write data to the destination. class HelloWorld { public static void main(String[] args) { System.out.println("Hello, World!"

What are the stream classes in Java?

There are two basic types of stream defined by Java, called byte stream and character stream. The byte stream classes provide a convenient means for handling input and output of bytes and character streams provide a convenient means for handling input and output of characters, respectively.


2 Answers

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

like image 94
Rostislav Matl Avatar answered Sep 22 '22 12:09

Rostislav Matl


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.

like image 35
Chip McCormick Avatar answered Sep 21 '22 12:09

Chip McCormick