4

The requirement is to monitor multiple folders and file for any changes in UNIX. I need to be able to hook my java code for any changes like create/modify/delete. Could anybody suggest any java based frameworks to do the same?

Mithun
  • 7,747
  • 6
  • 52
  • 68

3 Answers3

4

If you use Java 7, you can use the WatchService API to monitor changes to the file system.

If you are stuck with Java 6-, you can have a look at some alternatives proposed in this post or this other one.

Community
  • 1
  • 1
assylias
  • 321,522
  • 82
  • 660
  • 783
  • We have a restriction to use only java 6. Could you please suggest any framework that is compatible with java 6, and open-source? – Mithun Feb 11 '13 at 10:51
  • @Mithun I have added two links with java 6 compatible libraries. – assylias Feb 11 '13 at 10:54
2

Have you looked at Java 7's File Notifier service ?

The java.nio.file package provides a file change notification API, called the Watch Service API. This API enables you to register a directory (or directories) with the watch service. When registering, you tell the service which types of events you are interested in: file creation, file deletion, or file modification. When the service detects an event of interest, it is forwarded to the registered process. The registered process has a thread (or a pool of threads) dedicated to watching for any events it has registered for. When an event comes in, it is handled as needed.

JNotify is a similar service/library for those who can't use Java 7.

Brian Agnew
  • 268,207
  • 37
  • 334
  • 440
1

Java 7 has introduced WatchService which watches registered objects for changes and event.

Example -

Path myDir = Paths.get("D:/test");       

    try {
       WatchService watcher = myDir.getFileSystem().newWatchService();
       myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE, 
       StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);

       WatchKey watckKey = watcher.take();

       List<WatchEvent<?>> events = watckKey.pollEvents();
       for (WatchEvent event : events) {
            if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
                System.out.println("Created: " + event.context().toString());
            }
            if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {
                System.out.println("Delete: " + event.context().toString());
            }
            if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {
                System.out.println("Modify: " + event.context().toString());
            }
        }

    } catch (Exception e) {
        System.out.println("Error: " + e.toString());
    }
}
Subhrajyoti Majumder
  • 40,646
  • 13
  • 77
  • 103