简体   繁体   中英

Monitor file/folders to get change notifications in UNIX

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?

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 .

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.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM