Paulo Guedes
Paulo Guedes

Reputation: 7259

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

Upvotes: 1

Views: 934

Answers (4)

Ben S
Ben S

Reputation: 69342

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
}

Upvotes: 3

Jerry Coffin
Jerry Coffin

Reputation: 490128

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.

Upvotes: 1

Brian Agnew
Brian Agnew

Reputation: 272277

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)

Upvotes: 1

Kevin
Kevin

Reputation: 30419

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.

Upvotes: 4

Related Questions