加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Java > 正文

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

发布时间:2020-12-14 05:28:20 所属栏目:Java 来源:网络整理
导读:我想要看一个选择的文件夹进行更改,那么如果在其中添加/删除/删除内容,我需要获取有关文件夹和子文件夹中的所有文件的信息.我正在使用WatchService,但它只监视一个路径,它不处理子文件夹. 这是我的方法: try { WatchService watchService = pathToWatch.get
我想要看一个选择的文件夹进行更改,那么如果在其中添加/删除/删除内容,我需要获取有关文件夹和子文件夹中的所有文件的信息.我正在使用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参数.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读