** public Boolean watchDirectory(String dirPath) {// Check whether the directory to be monitored exists if (! (new File(dirPath).exists()) {log.error(messageformat.format (" directory {0} does not exist! ") , dirPath)); return false; } // Register the folder to monitor Path watchDirectory = Path.get (new File(dirPath).getPath()); try (WatchService watchService = FileSystems.getDefault().newWatchService()) { watchDirectory.register(watchService, / / to monitor the specified file type operation, create/modify/delete 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(); / / execution if the file is created (eventKind = = StandardWatchEventKinds. ENTRY_CREATE) {/ / TODO: }} // Reset after each execution. Boolean isKeyValid = watchkey.reset (); if (! isKeyValid) { break; } } } catch (IOException | InterruptedException e) { e.printStackTrace(); } return true; }Copy the code