When using getresourceasstream, the findbugs “method may not be able to close the stream”
If I have the following code in the servlet:
Properties p = new Properties(); p.load(getClass().getResourceAsStream("/test.properties"));
If I run the servlet through findbugs, I want to be warned_ OPEN_ Stream, but I didn't If I use a similar method to open any file on the file system (i.e. 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, the warning does not exist because findbugs lacks a valid warning (that is, I should close the flow in the finally block after loading into the properties object) or is there any reason why I don't need to close the flow?
thank you
rich
Solution
Take a look at the description of the warning:
In the first case, your code does not create a stream, it asks the class loader to provide it Therefore, findbugs will not assume that your code is responsible for closing the flow, possibly to avoid false positives
Note that the class loader can implement getresourceasstream () without closing the stream (that is, by copying the resource into memory and returning bytearrayinputstream) However, for the common case of urlclassloader loading classes from the directory, it is really necessary to close the stream to avoid leaking the file handle