To the contrary, I believe it is indeed possible for the key to get both events. Per the WatchKey Javadocs, "Events are retrieved by invoking the key's pollEvents method. This method retrieves and removes all events accumulated for the object."
To show how both events could accumulate, I tried adding the following code just before the
while loop:
Code: Select all
Path file = Paths.get(directoryPath, "testFile.txt");
Files.createFile(file);
Files.delete(file);
I get the output:
true
sun.nio.fs.AbstractWatchKey$Event@7ea987ac
sun.nio.fs.AbstractWatchKey$Event@12a3a380
and for clarity, changing println(watchEvent) to println(kind + " " + watchEvent):
true
ENTRY_CREATE sun.nio.fs.AbstractWatchKey$Event@7ea987ac
ENTRY_DELETE sun.nio.fs.AbstractWatchKey$Event@12a3a380
confirming the two events gotten.
One more consideration is that a file creation could possibly result in one or more ENTRY_MODIFY events in addition to the ENTRY_CREATE event, depending on how the file is created. For example, when I instead create a file in the watched directory at the command line (e.g., "echo > testFile" or "copy file1 file2") sometimes I get:
true
ENTRY_CREATE sun.nio.fs.AbstractWatchKey$Event@7ea987ac
ENTRY_MODIFY sun.nio.fs.AbstractWatchKey$Event@12a3a380
So in this way as well, more than one event could be received even without calling reset() on the key.