• An object implementing the Watchable interface – the Path class is perfect for this job.
• A set of events that we are interested in – we will use StandardWatchEventKind which implements the WatchEvent.Kind<T>.
• An event modifier that qualifies how a Watchable is registered with a WatchService.
• A watcher who watch some watchable – per example, a watcher that watches the File System for changes. The abstract class is java.nio.file.WatchService but we will be using the FileSystem object to create a watcher for the File System.
The below example follows the above scenario:
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKind;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;
public class Main {
public static void main(String[] args) {
//define a folder root
Path myDir = Paths.get("D:/data");
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 FileSystem object and the WatchService can also be created like this:
- FileSystem fileSystem = FileSystems.getDefault();
- WatchService watcher = fileSystem.newWatchService();
And the Path (watchable), what we watch, and register it with the WatchService object like this:
-
Path myDir = fileSystem.getPath(
“D:/data”
); - myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE,
-
StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);