Search code examples
javajava-io

Resource leak: 'in' is never closed, though it IS closed


I know that there are a couple of similarly entitled questions out there, but most of them have simply forgotten to put a close() directive on their stream. This here is different.

Lets say I have the following minimal example:

public void test() throws IOException
{
    InputStream in;
    if( file.exists() )
    {
        in = new FileInputStream( file );
    }
    else
    {
        in = new URL( "some url" ).openStream();
    }
    in.close();
}

This give me a Resource leak: 'in' is never closed warning in Eclipse (Juno SR1). But when I move the in.close() into the conditional block, the warnings vanishes:

public void test() throws IOException
{
    InputStream in;
    if( file.exists() )
    {
        in = new GZIPInputStream( new FileInputStream( file ) );
        in.close();
    }
    else
    {
        in = new URL( "some URL" ).openStream();
    }
}

What is going on here?


Solution

  • Here's how I'd write it:

    public void test() throws IOException
    {
        InputStream in = null;
        try {
            if(file.exists()) {
                in = new FileInputStream( file );
            } else {
                in = new URL( "some url" ).openStream();
            }
            // Do something useful with the stream.
        } finally {
            close(in);
        }
    }
    
    public static void close(InputStream is) {
        try {
            if (is != null) {
                is.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }