微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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参数.

原文地址:https://www.jb51.cc/java/122420.html

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐