Reputation: 8067
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?
Upvotes: 4
Views: 3556
Reputation: 41200
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());
}
}
Upvotes: 1
Reputation: 328568
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.
Upvotes: 4
Reputation: 272217
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.
Upvotes: 2