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?
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With