我试图检测文件夹中的文件创建,但是WatchService无法检测第二个文件创建。卡在key = watcher.take()上。知道为什么吗?我正在使用Ubuntu 11.04 x86。

private void watchWorkingDirectory() {
    try {
        WatchService watcher = FileSystems.getDefault().newWatchService();
        WatchKey key;
        key = Paths.get(tailSource, "").register(watcher, ENTRY_CREATE);

        for (;;) {

            System.err.println("Watching current working directory...............................................");
            // wait for key to be signalled
            key = watcher.take();

            System.out.println("Event detected:");


            for (WatchEvent<?> event : key.pollEvents()) {
                WatchEvent.Kind<?> kind = event.kind();

                if (kind == ENTRY_CREATE) {
                    tailSource = event.context().toString();
                    System.out.println(tailSource);
                    File file = new File(tailSource);
                    BufferedReader br = new BufferedReader(new FileReader(file));
                    System.out.println(br.readLine());
                    tailer = new Tailer(file, tListener, 1, false);
                    (new Thread(tailer)).start();
                }
            }
        }

    } catch (IOException | InterruptedException e) {
        System.out.println(e.getMessage());
    }
}


}

最佳答案

您必须在处理事件后调用key.reset()。

http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes

关于java - Java:nio WatchService-无法检测到第二个文件的创建。为什么?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/7413817/

10-10 14:10
查看更多