I'm working on a Java app and I need to check if a removable drive is in use before ejecting it programatically.
Is it possible to check a drive for open/in-use files in pure Java? As a fallback, is there a shell command that I could call from Java which would do this kind of checking? Ideally, I'd need commands for both Windows and MacOS.
In Java, directly checking if a drive is in use (i.e., if files on the drive are open) is not straightforward due to platform-independent restrictions and security concerns. However, you can use platform-specific methods to achieve this indirectly.
For Windows, you can execute the
'handle'
command-line tool using Java'sProcessBuilder
to check for open handles on a specific drive. Here's an example:For maxOS, you can use the
'lsof'
command to list open files. Something like this may work depending on your usecase: