I am writing tests for some Java file handling code and want to make sure all files are closed properly. I don't want to run 'lsof' as that will open more files and make the test suite non-portable. Anyone know a way to do this?
If you're looking for something that's part of the JDK, the answer is no.
You might find something that uses JVMTI, but that wouldn't be portable (it's a native interface). Or something that uses JPDA, but that would require a second JVM. I give you those two acronyms as a start for Googling.
If you want to run in-JVM and be portable, you'll have to introduce a factory for your file references: replace all new FileInputStream()
, new FileOutputStream()
, new RandomAccessFile()
, new FileReader
, and new FileWriter
calls with methods on that factory object. This factory will return subclasses of these objects, that have the close()
method overridden. It will also increment an "open files" counter, that is then decremented by the overridden close()
.
The factory methods and counter will need to be static and synchronized (unless you want to inject the factory), and should use a system property to decide whether to return a subclassed stream or the JDK version.
Personally, I'd take the advice in the comment, and use FindBugs first.
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