I stumbled on a false positive telling me that I haven't closed an OutputStream.
Reference type java.io.OutputStream
1 instances of obligation remaining
…
Remaining obligations: {OutputStream x 1}
The code
FileOutputStream fileOutputStream = null; try { fileOutputStream = new FileOutputStream(path); fileOutputStream.write(data); } catch (Exception e) { log.w("Could not save file", e); } finally { IOUtils.close(fileOutputStream); }
The method in IOUtils looks like this
public static void close(... streams) { for (Closeable closeable : streams) { if (closeable != null) { try { closeable.close(); } catch (IOException e) { log.w("IO.close() - Failed to close stream", e); } } } }
If I copy the contents of the utility method into finally block no problem is detected.
I suggest to NOT fix this as the user should use the try-with-resources statement on auto-closable resources:
That's not at all an appropriate solution to the false-positive.
You should not enforce using try-with-resources.
First the piece I sent is a valid code, so FindBugs shouldn't report a problem that's not there.
And second you cannot always use try-with-resources! On Android you can use it only if your minSdkVersion is 19 (Android 4.4) and that's not acceptable for most of the applications.
I generally agree with you but it's just not realistic to expect Findbugs to know about IOUtils.close(fileOutputStream).
What if other users use some other method that eventually closes the stream(s)? How many levels of method invocations should Findbugs follow (if it could) to evaluate if the resource is closed or not?