我想要看一个选择的文件夹进行更改,那么如果在其中添加/删除/删除内容,我需要获取有关文件夹和子文件夹中的所有文件的信息.我正在使用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
有没有更好的解决方案?
解决方法
WatchService只会监视您注册的路径.它不会递归地通过这些路径.
给定/根作为注册路径
/Root /Folder1 /Folder2 /Folder3
如果Folder3中有更改,将不会捕获它.
您可以自行以递归方式注册目录路径
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; } }); }