1

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

4

2 回答 2

2

在所有评论之后,并且由于您的问题看起来特定于 Windows,我想建议以下库:

http://jpathwatch.wordpress.com/

如果您阅读功能,您可以看到以下内容:

子目录的变化*(递归监控)

这就是你需要的。似乎它可以为您完成,而无需您手动注册每个新目录。它仅限于选定的平台。并且在检查时,似乎仅在 Windows 中可用!!!!见这里:http: //jpathwatch.wordpress.com/documentation/features/

一个非常重要的事情是当监视目录变得不可用时失效的可能性。(使用 java watch 服务,一个目录被监控并被重命名,你仍然会得到旧路径的事件!!)

我认为这个库将是最优雅的,并且会为你节省大量的编码。

于 2013-08-10T17:24:19.890 回答
2

取自这里

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();
}
于 2013-08-10T16:13:19.157 回答