如何查看文件夹和子文件夹的更改 [英] How to watch a folder and subfolders for changes
问题描述
我正在尝试查看特定文件夹的更改,然后,如果其中发生任何添加/修订/删除,我需要获取该文件夹及其子文件夹中所有文件的更改类型.我为此使用WatchService
,但它仅监视单个路径,不处理子文件夹.
I´m trying to watch a specific folder for changes, and then if any addition/edition/removal happens inside of it, I need to get the change type of all files in that folder and its subfolders. I'm using WatchService
for this but it only watches a single path, it doesn't handle subfolders.
这是我的方法:
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;
}
就像我之前说过的那样,我只获取所选路径中文件的日志,我想观看所有文件夹和子文件夹文件,例如:
Like I said before, I'm getting the log only for the files in the selected path, and I want to watch all folders and subfolders files, something like:
示例1:
FileA (Created)
FileB
FileC
FolderA FileE
FolderA FolderB FileF
示例2:
FileA
FileB (Modified)
FileC
FolderA FileE
FolderA FolderB FileF
有没有更好的解决方案?
Is there any better solution?
推荐答案
WatchService
仅监视您注册的Path
.它不会递归地通过这些路径.
A WatchService
only watches the Path
s you register. It does not go through those paths recursively.
给出/Root
作为注册路径
/Root
/Folder1
/Folder2
/Folder3
如果Folder3
中有更改,它将无法捕获.
If there is a change in Folder3
, it won't catch it.
您可以自己用递归方式注册目录路径
You can register the directory paths recursively yourself with
private void registerRecursive(final Path root) throws IOException {
// register all subfolders
Files.walkFileTree(root, new SimpleFileVisitor<Path>() {
@Override
public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
dir.register(watchService, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
return FileVisitResult.CONTINUE;
}
});
}
现在,WatchService
将通知Path root
的所有子文件夹中的所有更改,即.您传递的Path
参数.
Now the WatchService
will notify all changes in all subfolders of Path root
, ie. the Path
argument you pass.
这篇关于如何查看文件夹和子文件夹的更改的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!