0

I need to monitor a given directory and all its sub directories for changes (Especially addition of files and directories).

My current code is as follows

Path watchFolder = Paths.get("D:/watch");
    WatchService watchService = FileSystems.getDefault().newWatchService();
    watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
            watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_DELETE);
            watchFolder.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);

    boolean valid = true;
    do {
        WatchKey watchKey = watchService.take();

        for (WatchEvent event : watchKey.pollEvents()) {
            WatchEvent.Kind kind = event.kind();
            if (StandardWatchEventKinds.ENTRY_CREATE.equals(kind)) {
                String fileName = event.context().toString();
                System.out.println("File Created:" + fileName);
            }
        }
        valid = watchKey.reset();

    } while (valid);

This code is only able to monitor the parent directory changes. If I add a directory in the parent directory, it is able to fire the event. But, if I add a file inside sub-directory, it is not able detect.

FYI : I also tried JNotify, but it keeps saying java.lang.UnsatisfiedLinkError: no jnotify_64bit in java.library.path

Is there any better solution than these?

Sunil Kumar B M
  • 2,735
  • 1
  • 24
  • 31
  • 1
    I think this has already been answered here: http://stackoverflow.com/questions/17850940/watching-a-directory-and-sub-directory-for-create-modify-and-changes-in-java – fishi0x01 Jul 02 '15 at 11:33

2 Answers2

0

I would like to encourage you to give another try. It nicely reports changes in subdirectories and looks more resource efficient than creating a load of WatchKeys for each and every directory you want to track.

As for your UnsatisfiedLinkError, see How to set the java.library.path from Eclipse. I placed jnotify_64bit.dll (Windows here) in my project's base dir, and it worked. YMMV.

f_puras
  • 2,521
  • 4
  • 33
  • 38
-1

From your question, I assume that your requirement is to poll the directory and when some file comes do something, meaning call some method.

If I have understood correctly then you should try JPoller which reduces the complexity and does what you need. It also allows you to set polling interval and provides you with a handful of callback methods.

JavaYouth
  • 1,536
  • 7
  • 21
  • 39