Java - how to find out if a directory is being used by another process?

3.4k Views Asked by At

I want to use java 7's WatchService to monitor changes to a directory.
It seems it tries to lock the folder, and will throw an exception if it fails, but does not seem to provide any method of locking it before-hand / checking if it is already locked.

I need to know if a directory is currently being used by another a process or not. Since I can't lock it or open a stream to it (because it's a directory), I'm looking for something more intelligent than trying to modify it and sleeping if failed, or try/catch with sleep.

Ideally, I would like a blocking call until it is available.

EDIT: I can't seem to acquire a FileLock on the folder. When I try to lock the folder, I get "FileNotFoundException (access denied)". Googling suggests you can't use that object on a directory.

registration code:

WatchService watchService = path.getFileSystem().newWatchService()
path.register(watchService,
                    StandardWatchEventKinds.ENTRY_CREATE,
                    StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE)

Failing scenario:
Let's say I'm listening to a folder f for new creation.
If a sub-folder g is created in it, I want to listen to changes in g. However, if I create a new folder in f (in Windows), this will fail because Windows is locking the folder until a name is given.

Thanks

2

There are 2 best solutions below

1
On

Taken from here

File file = new File(fileName);
FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
// Get an exclusive lock on the whole file
FileLock lock = channel.lock();
try {
    lock = channel.tryLock();
    // Ok. You get the lock
} catch (OverlappingFileLockException e) {
    // File is open by someone else
} finally {
    lock.release();
}
1
On

After all the comments, and since your problem looks particular to windows, I wanted to suggest the following library:

http://jpathwatch.wordpress.com/

if you read in the features, you can see the following:

Changes in subdirectories* (recursive monitoring)

this is what you need. seems it does it for you without you having to register every new directory by hand. it is limited to selected platforms. and when checking that, it seems that is available only in windows !!!! see here: http://jpathwatch.wordpress.com/documentation/features/

a very important thing is the possibility to invalidate when a watched directory becomes unavailable. (using java watch service, it a directory is monitored and gets renamed, you still get events with the old path !!)

I think this library would be the most elegant and will save a lot of coding for you for this case.