Java 7 WatchService - Ignoring multiple occurrences of the same event

后端 未结 14 604
情歌与酒
情歌与酒 2020-12-05 02:21

The javadoc for StandardWatchEventKinds.ENTRY_MODIFY says:

Directory entry modified. When a directory is registered for this event the

14条回答
  •  醉梦人生
    2020-12-05 02:42

    Are you sure there is problem with jdk7? It gives correct result for me (jdk7u15, windows)

    Code

    import java.io.IOException;
    import java.nio.file.*;
    
    public class WatchTest {
    
        public void watchMyFiles() throws IOException, InterruptedException {
            Path path = Paths.get("c:/temp");
            WatchService watchService = path.getFileSystem().newWatchService();
            path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
    
            while (true) {
                WatchKey watchKey = watchService.take(); // blocks
    
                for (WatchEvent event : watchKey.pollEvents()) {
                    WatchEvent watchEvent = (WatchEvent) event;
                    WatchEvent.Kind kind = watchEvent.kind();
    
                    System.out.println(watchEvent.context() + ", count: " +
                            watchEvent.count() + ", event: " + watchEvent.kind());
                    // prints (loop on the while twice)
                    // servers.cfg, count: 1, event: ENTRY_MODIFY
                    // servers.cfg, count: 1, event: ENTRY_MODIFY
    
                    switch (kind.name()) {
                        case "ENTRY_MODIFY":
                            handleModify(watchEvent.context()); // reload configuration class
                            break;
                        case "ENTRY_DELETE":
                            handleDelete(watchEvent.context()); // do something else
                            break;
                        default:
                            System.out.println("Event not expected " + event.kind().name());
                    }
                }
    
                watchKey.reset();
            }
        }
    
        private void handleDelete(Path context) {
            System.out.println("handleDelete  " + context.getFileName());
        }
    
        private void handleModify(Path context) {
            System.out.println("handleModify " + context.getFileName());
        }
    
        public static void main(String[] args) throws IOException, InterruptedException {
            new WatchTest().watchMyFiles();
        }
    }
    

    Output is like below- when file is copied over or edited using notepad.

    config.xml, count: 1, event: ENTRY_MODIFY
    handleModify config.xml
    

    Vi uses many additional files, and seems to update file attribute multiple times. notepad++ does exactly two times.

提交回复
热议问题