java – 如何查看文件夹和子文件夹进行更改

我想要看一个选择的文件夹进行更改,那么如果在其中添加/删除/删除内容,我需要获取有关文件夹和子文件夹中的所有文件的信息.我正在使用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;
        }
    });
}

现在,WatchService将通知Path root的所有子文件夹中的所有更改,即.你通过的Path参数.

相关文章

最近看了一下学习资料,感觉进制转换其实还是挺有意思的,尤...
/*HashSet 基本操作 * --set:元素是无序的,存入和取出顺序不...
/*list 基本操作 * * List a=new List(); * 增 * a.add(inde...
/* * 内部类 * */ 1 class OutClass{ 2 //定义外部类的成员变...
集合的操作Iterator、Collection、Set和HashSet关系Iterator...
接口中常量的修饰关键字:public,static,final(常量)函数...