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