For example, if you want WatchService
to detect that dir \ file.txt
has changed, you'll want to write code like this, which raises a runtime exception (NotDirectoryException
).
var file = Paths.get("dir", "file.txt");
var watcher = FileSystems.getDefault().newWatchService();
file.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
[JavaDoc for Path :: register
](https://docs.oracle.com/javase/jp/8/docs/api/java/nio/file/Path.html#register-java.nio.file.WatchService As you can see in -java.nio.file.WatchEvent.Kind: A-java.nio.file.WatchEvent.Modifier ...-), the registration target of WatchService
is a directory. Or it can be said that WatchService
monitors the events that occur in the files and directories under the registered directory. Therefore, if you want to detect only the events of a specific file, you need to devise the following, for example.
var file = Paths.get("dir", "file.txt");
var directory = file.getParent();
var watcher = FileSystems.getDefault().newWatchService();
directory.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
//File until interrupted by interrupt etc..Keep monitoring txt.
while (true) {
var watchKey = watcher.take();
for (var event : watchKey.pollEvents()) {
var modified = (Path) event.context();
if (modified.equals(file.getFileName())) {
// Do Something
}
}
}
You can get information about the entry where the event occurred with WatchEvent :: context
. The return value of WatchEvent :: context
is ʻObject, but in reality, a
Pathobject is returned, so in the above example, it is cast as a variable
modified`.
Also, the Path
object stored in modified
is a relative path from the directory registered in WatchService
. In short, it is var modified = Paths.get ("file.txt ");
, so you need to be careful when comparing with ʻequals` etc.
Recommended Posts