Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to properly close a FileChannel obtained from a FileOutputStream

I just opened some old code in the current Eclipe Juno Release Candidate and noticed a shiny new warning: Resource leak. It was triggered by code like this:

FileChannel out = new FileOutputStream(file).getChannel();
try
{
    ...Do something with out...
}
finally
{
    out.close();
}

Eclipse thinks that the created file output stream is a resource leak. Actually I'm not sure if this is a false warning (And the close method of the FileChannel doesn't close the stream, too) or if this is really a resource leak. I changed the code to this:

FileOutputStream outStream = new FileOutputStream(file);
try
{
    FileChannel out = outStream.getChannel();
    ...Do something with out...
}
finally
{
    outStream.close();
}

The warning is gone now but now I'm not sure if the close method of the FileChannel must be called. So maybe it must look like this:

FileOutputStream outStream = new FileOutputStream(file);
try
{
    FileChannel out = outStream.getChannel();
    try
    {
        ...Do something with out...
    }
    finally
    {
        out.close();
    }
}
finally
{
    outStream.close();
}

If using a file input channel and a file output channel then this results in four nested try...finally blocks and it all gets kind of bloated.

What do you think? Is it really necessary to close the channel AND the stream? Or is closing the stream enough?

like image 887
kayahr Avatar asked Jan 17 '23 09:01

kayahr


1 Answers

Ah, found the answer in the documentation of the close() method of FileOutputStream:

If this stream has an associated channel then the channel is closed as well.

So closing the stream is enough.

like image 170
kayahr Avatar answered Jan 31 '23 00:01

kayahr