views:

65

answers:

1

Hi

If I have the following code in a servlet:

Properties p = new Properties();
p.load(getClass().getResourceAsStream("/test.properties"));

If I run the servlet through FindBugs, I would expect to get the warning OS_OPEN_STREAM, but I don't. If I use a similar approach to open an arbitrary file on the filesystem (ie not in the classpath), I get the Findbugs warning as expected:

Properties p = new Properties();
p.load(new FileInputStream(new File("c:/test.properties")));

In the first example, is the warning absent because Findbugs is missing a valid warning (ie I should be closing the stream in a finally block after loading into the Properties object) or is there a reason I don't need to close the stream?

Thanks

Rich

+6  A: 

Look at the description of the warning:

The method creates an IO stream object, does not assign it to any fields...

In your first case, your code does not create the stream, it asks the classloader to give it a stream. Thus, Findbugs does not consider your code responsible for closing the stream, probably to avoid false positives.

Note that a classloader could implement getResourceAsStream() in a way that does not require the stream to be closed (i.e. by copying the resource into memory and returning a ByteArrayInputStream). But for the common case of an URLClassLoader loading classes from a directory, closing the stream is indeed necessary to avoid leaking file handles.

Michael Borgwardt
I believe it's just an oversight on findbug's part. Close the stream.
MeBigFatGuy