我想要监视一个特定的文件夹以便获取其中文件的修改类型,包括添加、编辑或删除,并且需要监视该文件夹及其子文件夹中所有文件的变化。我正在使用WatchService
实现,但它只能监视单个路径,无法处理子文件夹。
这是我的解决方案:
try {
WatchService watchService = pathToWatch.getFileSystem().newWatchService();
pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
// loop forever to watch directory
while (true) {
WatchKey watchKey;
watchKey = watchService.take(); // This call is blocking until events are present
// Create the list of path files
ArrayList<String> filesLog = new ArrayList<String>();
if(pathToWatch.toFile().exists()) {
File fList[] = pathToWatch.toFile().listFiles();
for (int i = 0; i < fList.length; i++) {
filesLog.add(fList[i].getName());
}
}
// Poll for file system events on the WatchKey
for (final WatchEvent<?> event : watchKey.pollEvents()) {
printEvent(event);
}
// Save the log
saveLog(filesLog);
if(!watchKey.reset()) {
System.out.println("Path deleted");
watchKey.cancel();
watchService.close();
break;
}
}
} catch (InterruptedException ex) {
System.out.println("Directory Watcher Thread interrupted");
return;
} catch (IOException ex) {
ex.printStackTrace(); // Loggin framework
return;
}
就像我之前说的,我只是为所选路径中的文件获取日志,而我想监视所有文件夹和子文件夹中的文件,类似于:
示例1:
FileA (Created)
FileB
FileC
FolderA FileE
FolderA FolderB FileF
例子2:
FileA
FileB (Modified)
FileC
FolderA FileE
FolderA FolderB FileF
有更好的解决方案吗?