views:

378

answers:

5

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?

+1  A: 

Something quite low level and OS-specific like that is going to need native code (as per the link you mention). That library looks relatively small, so in the worst case you could probably fix any problems if your C++ is good enough.

If you can at all avoid it though, I'd suggest not using native code - library or not. What is so demanding about your scenario that you can't have a background thread poll?

Draemon
+4  A: 

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);
}
Brian
Nice, I didn't know that.
Draemon
If this is for production code Java 7 should not be used. It isn't released.
Alain O'Dea
A: 

If not using Jdk7 you'll have to use JNI.

John Doe
+2  A: 

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

dblock
+1  A: 

Brian Agnew's recommendation of JNotify is a good one: http://stackoverflow.com/questions/1096404/is-there-a-sophisticated-file-system-monitor-for-java-which-is-freeware-or-open-s/1096876#1096876

Description from http://jnotify.sourceforge.net/:

JNotify is a java library that allow java application to listen to file system events, such as:

  • File created
  • File modified
  • File renamed
  • File deleted
Alain O'Dea