skiphoppy
skiphoppy

Reputation: 102723

How can I tell what processes are using a file under Java in Windows?

We have a scheduled task written in Java that is failing on Windows platforms because sometimes the files it needs to delete are still in use. Is there a way from within Java that I can see what processes are using a file and get information on them?

I thought I would add that I am willing to use JNA or JNI if necessary, and I assume it is going to be.

Upvotes: 11

Views: 4112

Answers (4)

IvanRF
IvanRF

Reputation: 7265

I asked a similar question on Github for the JNA project and @matthiasblaesing wrote a code to accomplish this.

The code is here.

It prints a list with all the running processes in the format: <exe>: <type>: <path>.

Upvotes: 3

skiphoppy
skiphoppy

Reputation: 102723

My own preliminary answer (please, someone do better!):

Ideally, I'd like to learn how to programmatically do what tools like Process Explorer, unlocker, handler, etc., do, and then call that from Java with JNA or similar. But it looks like that involves data structures that change for each Windows release, so it sounds very fragile. The system call involved appears to be named NtQuerySystemInformation.

It looks like in cases like we are dealing with, the preferred approach for Windows Vista onward is to use the "restart manager API," which triggers a system restart, clearing all open filehandles. (source: http://social.msdn.microsoft.com/Forums/sv/netfxbcl/thread/37dc9843-2583-41fc-8260-b78183aa4bed) We sure don't want to do that, if we can help it.

Upvotes: 1

Anthony Accioly
Anthony Accioly

Reputation: 22461

One dirty way to do it is to run your application with administrative privileges and invoke a command utility such as Handle using a ProcessBuilder.

Upvotes: 2

cheeken
cheeken

Reputation: 34655

You can use the excellent Sysinternals Process Explorer to do this, and it's not limited to Java processes.

See this posting for details. I don't know how to invoke this functionality from java, however.

Upvotes: 1

Related Questions