Sunday, July 31, 2011

Java 7 Warning with the behaviour of WatcherService ?



I look at new functionnality for WatcherService.So I created a directory and I watch for events like files created or deleted or modify.I follow the example from http://blogs.oracle.com/thejavatutorials/entry/watching_a_directory_for_changes
I was surprised for an unexpected  behaviour with WatcherService :


I make the following :
mkdir ~/tmp
touch ~/tmp/toto


Then I watched for events in ~/tmp/toto and it works fine.

Then I do the following :

mv ~/tmp ~/tmp.old
touch ~/tmp.old/titi


I look at events and there is events ! However I move the directory so the program should be throw an exception because of reset methods() but no !
So I post a message (It's the first time I post a message on the Oracle's web site !!!! ) and I wait for an answer ...
I will see if I post a good note ....


Here is the example source code form Oracle'sblog :

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();

        //This key is registered only for ENTRY_CREATE events,
        //but an OVERFLOW event can occur regardless if events are
        //lost or discarded.
        if (kind == OVERFLOW) {
            continue;
        }

        //The filename is the context of the event.
        WatchEvent ev = (WatchEvent)event;
        Path filename = ev.context();

        //Verify that the new file is a text file.
        try {
            //Resolve the filename against the directory.
            //If the filename is "test" and the directory is "foo",
            //the resolved name is "test/foo".
            Path child = dir.resolve(filename);
            if (!Files.probeContentType(child).equals("text/plain")) {
                System.err.format("New file '%s' is not a plain text file.%n", filename);
                continue;
            }
        } catch (IOException x) {
            System.err.println(x);
            continue;
        }

        //Email the file to the specified email alias.
        System.out.format("Emailing file %s%n", filename);
        //Details left to reader....
    }

    //Reset the key -- this step is critical if you want to receive
    //further watch events. If the key is no longer valid, the directory
    //is inaccessible so exit the loop.
    boolean valid = key.reset();
    if (!valid) {
        break;
    }
}




No comments:

Post a Comment