开发者

How do I create a monitor for a specific directory?

Using Java over Windows Vista, I'm trying to create a kind of a monitor for a directory, so every time this directory is modified (new, renamed, updated or deleted files) a process is triggered. I tried to do this with a loop that will execute a dir in the directory and analyze all the files. But this is very time and memory consuming, specially when 开发者_运维问答the number of files start to grow. I think there should be a better way to do that.

note: there is a similar question in SO for this, but it's for C#.


I think there should be a better way to do that.

You're right, there should be a better way and its coming with Java 7. See the upcoming WatchService API.

Without getting an RC build, I don't know if there is a portable way to do what you describe.


If you can't wait for Java 7 and the WatchService you'll have to do something like this:

final File watched = new File("[path of directory to watch]");
long lastModified = watched.lastModified();
while(true) {
    if (watched.lastModified() > lastModified) {
        // Change happened in the directory do what you want.
    }
    Thread.sleep(2000); // 2 second interval
}


What exactly are you monitoring ? I would expect that you should simply have to monitor the modification time of the directory, and then check the modification times of the files if the directory has been modified.

So I would expect to store a Map of filenames vs. modification times (for the checking at least).

Unfortunately there isn't an easy means to use Java to check a directory for changes other than polling the directory in some capacity. See a previous answer of mine wrt. this question and libraries you can use to simplify this (plus the Java 7 feature)


You'll probably need to use JNI to call ReadDirectoryChangesW. You could use FirstFirstChangeNotification and FindNextChangeNotification instead, but unless you need compatibility with old (16-bit) versions of Windows, I'd advise against it.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜