Search code examples
javafilefile-ioio

How can I find out which object has a file open in Java?


I need to find out which object in my Java app has a file open. This is for debugging, so tools or utilities are welcome.

If finding which object is too specific, which class would also be very helpful.


Solution

  • That could be tricky. You could start by using a profiler, like VisualVM (free) or YourKit (not free) to inspect java.io.File objects in memory. If you can find one with the path you're interested in, that might point you in the right direction. The problem is that a File object doesn't necessarily have to exist for an app to still have the file open.

    Your next step might be to set breakpoints in both FileInputStream and FileOutputStream (unless you know whether the file is being read or written to), attach a debugger, and watch for your file to be opened by one of those. But of course, there are other ways of opening files as well. You might also need to stake out things like Class.getResourceAsStream() and URL.openConnection(), for example.

    Your last resort might be to try out an omniscient debugger, like ODB or TOD. I only have limited experience with them, but they claim to "know everything". You'll just have to figure out how to ask the right question.