Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I receive Windows filesystem events in Java?

I need to know when a new file appears in a directory. Obviously, I could poll the file system periodically, but that has all the normal downsides of polling mechanisms.

I know that windows supports file system events, and this project is already constrained to the Windows platform by other requirements.

Does anyone have experience receiving Windows filesystem events inside a JVM? If so what are the best practices, patterns, and/or libraries you have used?

A quick google turns up this library. Does anyone have experience with it (or any other) that they'd be willing to share?

like image 406
Jared Avatar asked Jul 21 '09 18:07

Jared


2 Answers

I think this is one of the key features of Java 7 when it is more available. Example code from Sun's blog on Java 7:

import static java.nio.file.StandardWatchEventKind.*;

Path dir = ...;
try {
    WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
} catch (IOException x) {
    System.err.println(x);
}
like image 133
Brian Avatar answered Sep 20 '22 08:09

Brian


For Java 6 or older use JNA's com.sun.jna.platform.win32.FileMonitor.

like image 25
dB. Avatar answered Sep 21 '22 08:09

dB.