我正在尝试查看特定文件夹的更改,然后如果其中发生任何添加/编辑/删除,我需要获取该文件夹及其子文件夹中所有文件的更改类型。我正在使用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
有没有更好的解决方案?