如何使用WatchService监视子目录中的更改? (Java) [英] How can I watch subdirectory for changes with WatchService? (Java)
本文介绍了如何使用WatchService监视子目录中的更改? (Java)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想查看一些目录中的更改及其子目录.我尝试使用 WatchService
,但我不知道从哪个目录更改了文件.如何从
I want to watch some directory for changes and her subdirectories. I tried to do this with WatchService
but I can't know from which directory the file was changed. How can I retrieve the full path from the WatchEvent
?
推荐答案
通常,在启动watchservice时会提供文件的目录名称.这是一个演示其工作原理的教程:
Generally you provide the directory name of the file when starting the watchservice. Here is a tutorial demonstrating how that works:
http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes
从教程开始:
Path dir = ...;
try {
WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
}[.....]
当您收到通知时:
//The filename is the context of the event.
WatchEvent<Path> ev = (WatchEvent<Path>)event;
Path filename = ev.context();
Path child = dir.resolve(filename);
这篇关于如何使用WatchService监视子目录中的更改? (Java)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文