The Java NIO (New I/O) package includes a way to watch for changes in files and directories using the WatchService API. This feature is extremely useful for applications that need to respond to changes in the file system, such as editors, backup utilities, and configuration watchers.
The WatchService API allows you to register directories for watching and respond to events like creation, modification, and deletion of files. Below is a simple example of how to use WatchService in Java.
import java.nio.file.*;
public class FileWatcherExample {
public static void main(String[] args) {
try {
// Create a WatchService
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("path/to/watch"); // Specify the path to watch
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
System.out.println("Watching directory: " + path);
while (true) {
// Wait for a watch key to be available
WatchKey key = watchService.take();
for (WatchEvent> event : key.pollEvents()) {
WatchEvent.Kind> kind = event.kind();
// Retrieve the file name associated with the event
WatchEvent ev = (WatchEvent) event;
Path fileName = ev.context();
System.out.println(kind.name() + ": " + fileName);
}
// Reset the key to receive further events
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?