Reputation: 2069
I am trying a small program from Pro Java 7 NIO.2 Page No 118
Code is :
class WatchRafaelNadal {
public void watchRNDir(Path path) throws IOException, InterruptedException {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
//start an infinite loop
while (true) {
//retrieve and remove the next watch key
final WatchKey key = watchService.take();
//get list of pending events for the watch key
for (WatchEvent<?> watchEvent : key.pollEvents()) {
//get the kind of event (create, modify, delete)
final Kind<?> kind = watchEvent.kind();
//handle OVERFLOW event
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
//get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
//print it out
System.out.println(kind + " -> " + filename);
}
//reset the key
boolean valid = key.reset();
//exit loop if the key is not valid (if the directory was deleted, for example)
if (!valid) {
break;
}
}
}
}
}
public class Main {
public static void main(String[] args) {
final Path path = Paths.get("C:/Java");
WatchRafaelNadal watch = new WatchRafaelNadal();
try {
watch.watchRNDir(path);
} catch (IOException | InterruptedException ex) {
System.err.println(ex);
}
}
}
But when I changed a line in global.properties
( or any file ) present in folder C:\\Java
I get output as -
ENTRY_MODIFY -> global.properties
ENTRY_MODIFY -> global.properties
Why it is raising event 2 times ?
Is there any service available in Java to detect exact modified line/lines in file ?
JDK : jdk1.7.0_09
IDE : Eclipse Java EE IDE Version : Juno Release
Platform : Windows 7
Upvotes: 0
Views: 331
Reputation: 77454
How did you change the file?
Maybe you technically changed the file twice.
For example, first the contents are changed, then the file meta data are updated, that makes two events.
It's probably best if you implement your application in a way that it can handle such situations.
Upvotes: 3