Search code examples
watchservice

Ubuntu Java watchservice is broken


This is my code to using monitor change folder:

    WatchService watcher = FileSystems.getDefault().newWatchService();
    Path dir = Paths.get("/home/user/test/");

    dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);

    System.out.println("Begin monitor to test folder: ");

    for (;;) {

        // wait for key to be signaled
        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

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

            // The filename is the
            // context of the event.
            @SuppressWarnings("unchecked")
            WatchEvent<Path> ev = (WatchEvent<Path>)event;
            Path filename = ev.context();

            if (filename.toString().startsWith(".")) continue;

            if (kind == OVERFLOW) {
                continue;
            } else if (kind == ENTRY_CREATE) {
                System.out.println(kind.name() + ":" +filename);
            } else if (kind == ENTRY_DELETE) {
                System.out.println(kind.name() + ":" +filename);
            } else if (kind == ENTRY_MODIFY) {
                System.out.println(kind.name() + ":" +filename);
            }

        }

        boolean valid = key.reset();
        if (!valid) {
            break;
        }
    }

It's great on windown, Mac os, However when run on ubuntu 16.04, I to face the problem: For existed files in watched folder: when I edit a file then I receiver create event, While i want to get modify event
Please help me

Thanks.


Solution

  • Make sure that the program you're using to edit the file with in Ubuntu doesn't create a hidden file. Some editors do this to make sure no changes are lost when the program crashes.

    So make sure that your editor does not create a hidden file when you're editing the file and if it does use another program or handle the hidden "subfile".