Jared
Jared

Reputation: 26149

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?

Upvotes: 7

Views: 3134

Answers (6)

Brian
Brian

Reputation: 13571

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);
}

Upvotes: 8

Ritesh
Ritesh

Reputation: 11

You can use opensource JPollar framework to poll the directory in time intervals. It also allows time based polling.

Upvotes: 1

Alain O'Dea
Alain O'Dea

Reputation: 21716

Brian Agnew's recommendation of JNotify is a good one: Is there a sophisticated file system monitor for Java which is freeware or open source?

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

Upvotes: 1

dB.
dB.

Reputation: 4770

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

Upvotes: 2

John Doe
John Doe

Reputation: 867

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

Upvotes: 0

Draemon
Draemon

Reputation: 34721

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?

Upvotes: 1

Related Questions