18

特定のフォルダーの変更を監視しようとしていますが、そのフォルダー内で追加/編集/削除が発生した場合は、そのフォルダーとそのサブフォルダー内のすべてのファイルの変更タイプを取得する必要があります。私は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

より良い解決策はありますか?

4

3 に答える 3

24

Aは、登録WatchServiceした s のみを監視しPathます。これらのパスを再帰的に通過することはありません。

/Root登録されたパスとして与えられる

/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渡す引数。

于 2013-09-09T15:03:39.017 に答える
5

Java 8 ストリームとラムダを使用して、このようなものを実装しました。

再帰的なフォルダーの検出は、Consumer @FunctionalInterfaceとして実装されます。

    final Map<WatchKey, Path> keys = new HashMap<>();

    Consumer<Path> register = p -> {
        if (!p.toFile().exists() || !p.toFile().isDirectory()) {
            throw new RuntimeException("folder " + p + " does not exist or is not a directory");
        }
        try {
            Files.walkFileTree(p, new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs) throws IOException {
                    LOG.info("registering " + dir + " in watcher service");
                    WatchKey watchKey = dir.register(watcher, new WatchEvent.Kind[]{ENTRY_CREATE}, SensitivityWatchEventModifier.HIGH);
                    keys.put(watchKey, dir);
                    return FileVisitResult.CONTINUE;
                }
            });
        } catch (IOException e) {
            throw new RuntimeException("Error registering path " + p);
        }
    };

上記のコードは、新しいフォルダーが作成されるたびに呼び出され、後の段階でフォルダーを動的に追加します。完全なソリューションと詳細については、こちらをご覧ください。

于 2016-06-06T13:03:47.333 に答える