Yoda
Yoda

Reputation: 18068

Watching directory changes by WatchService in Java 1.7

Since Java 1.7 there is a way of watching directory without adding additional libraries. On Oracle site there is a little tutorial how to use the WatchService http://docs.oracle.com/javase/tutorial/essential/io/notification.html#try but it is highly not understandable to me. There is no consitent example how to use it.

Therefore would someone kindly show me how to to add listener to directory and invoke method for example: f() when the file is added to directory let's say :"./folder" ?

Upvotes: 1

Views: 323

Answers (1)

benjamin.d
benjamin.d

Reputation: 2871

This piece of code will be called every time you create a file in your watched folder:

    Path path = new File("./folder").toPath();
    WatchService watchService = FileSystems.getDefault().newWatchService();
    path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
    for (;;) {
        try {
        WatchKey key = watchService.take();
        for (WatchEvent<?> event : key.pollEvents()) {
            WatchEvent.Kind<?> kind = event.kind();
            if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) {
                System.out.println("file created");
            }
        }
        } catch (InterruptedException x) {
             return;
        }
    }

Upvotes: 1

Related Questions