ticktock ticktock - 3 months ago 16
Java Question

Is this really a resource leak

FileOutputStream fos = new FileOutputStream(f, true);
FileChannel fileChannel = fos.getChannel();
FileWriter fileWriter = Channels.newWriter( fileChannel, Charset.forName("UTF-8").newEncoder(), -1 );
....
fileWriter.close()


I'm getting a compiler warning that since 'fos' isn't closed, I have a resource leak. I'm assuming, but have thus far failed to prove, that when I call 'fileWriter.close()', the resource is cleaned up.

Answer

No, it's not a resource leak but the compiler isn't smart enough to figure that out.

When you close your FileWriter, it closes the FileChannel, which in turn closes the FileOutputStream.

This of course, may not be the case with different JVM's. I've only looked at the code in the Oracle's Java8 rt.jar.

Since it's not stated as part of the public contract of FileWriter, it's a good idea to explicitly close all streams you create.