public boolean watchDirectory(String dirPath) {
if (!(new File(dirPath).exists())) {
log.error(MessageFormat.format("目录{0}不存在!", dirPath));
return false;
}
Path watchDirectory = Paths.get(new File(dirPath).getPath());
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
watchDirectory.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
WatchKey watchKey = watchService.take();
for (WatchEvent event : watchKey.pollEvents()) {
WatchEvent.Kind eventKind = event.kind();
if (eventKind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
String fileName = event.context().toString();
if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
}
}
boolean isKeyValid = watchKey.reset();
if (!isKeyValid) {
break;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return true;
}