views:

127

answers:

4

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#.

+4  A: 

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.

Kevin
+1  A: 

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)

Brian Agnew
+1  A: 

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.

Jerry Coffin
+1  A: 

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

final File watched = 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
}
Ben S
Your solution looks better than the one I'm using currently. I'll try it while Java 7 is not with me.
Paulo Guedes
You'll have to handle some possible exceptions being thrown in my code. `Thread.sleep()` and the IO operation can throw exceptions.
Ben S
I like TimeUnit.SECONDS.sleep(2) myself
Droo
you should set lastMofidied = watched.lastModified also inside the if Statement otherwise the statement is always true after the first change
Martin Dürrmeier