Java Reference
In-Depth Information
boolean shouldContinue = true;
while(shouldContinue) {
WatchKey key = service.poll(250,
TimeUnit.MILLISECONDS);
// Code to stop the program
while (System.in.available() > 0) {
int readChar = System.in.read();
if ((readChar == 'q') || (readChar == 'Q')) {
shouldContinue = false;
break;
}
}
if (key == null) continue;
key.pollEvents().stream()
.filter((event) -> !(event.kind() ==
StandardWatchEventKinds.OVERFLOW))
.map((event) ->
(WatchEvent<Path>)event).forEach((ev) -> {
Path filename = ev.context();
System.out.println("Event detected
:"+filename.toString()+" "+ev.kind());
});
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
How It Works
NIO.2 includes a built-in polling mechanism to monitor for changes in the FileSys-
tem . Using a poll mechanism allows you to wait for events and poll for updates at a
specified interval. Once an event occurs, you can process and consume it. A consumed
event tells the NIO.2 framework that you are ready to handle a new event.
Search WWH ::




Custom Search