Java Code Examples for java.nio.file.StandardWatchEventKinds#OVERFLOW
The following examples show how to use
java.nio.file.StandardWatchEventKinds#OVERFLOW .
You can vote up the ones you like or vote down the ones you don't like,
and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Main.java From java-cheat with GNU General Public License v3.0 | 6 votes |
public static void main(final String[] args) throws InterruptedException, IOException { final WatchService watchService = FileSystems.getDefault().newWatchService(); Paths.get(WATCH_DIR).register( watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); for (;;) { final WatchKey key = watchService.take(); for (final WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind kind = event.kind(); // TODO if (kind == StandardWatchEventKinds.OVERFLOW) continue; System.out.format("%s: %s\n", kind.name(), cast(event).context()); } key.reset(); } }
Example 2
Source File: FileWatcher.java From jfilter with Apache License 2.0 | 6 votes |
/** * Process all modify events * * @throws InterruptedException if interrupted while waiting */ @SuppressWarnings("unchecked") private void processModifiedFiles() throws InterruptedException { WatchKey key = watcher.take(); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { overflowed = true; continue; } if (watchKeys.containsKey(key)) { WatchEvent<Path> ev = (WatchEvent<Path>) event; String filename = String.format("%s%s%s", watchKeys.get(key).toString(), File.separator, ev.context().toString()); File file = new File(filename); if (fileIsModified(file)) fileRecords.get(file).onEvent(); } } key.reset(); }
Example 3
Source File: ExternalDatabaseLookupService.java From divolte-collector with Apache License 2.0 | 6 votes |
private void processWatchEvent(final Path parentDirectory, final WatchEvent<?> event) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { // Ignore these for now; we could treat this as a potential change. logger.warn("File notification overflow; may have missed database update."); } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { final Path modifiedRelativePath = (Path) event.context(); final Path modifiedAbsolutePath = parentDirectory.resolve(modifiedRelativePath); if (location.equals(modifiedAbsolutePath)) { logger.debug("Database has been updated; attempting reload: {}", modifiedAbsolutePath); reloadDatabase(); } else { logger.debug("Ignoring file modified event: {}", modifiedAbsolutePath); } } else { logger.debug("Ignoring file notification: {}", event); } }
Example 4
Source File: FileLock.java From scheduling with GNU Affero General Public License v3.0 | 5 votes |
@Override public void run() { while (running) { WatchKey key; try { key = watcher.take(); } catch (InterruptedException ex) { return; } for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path fileName = ev.context(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { if (fileName.equals(this.lockFile.getFileName())) { running = false; } } } boolean valid = key.reset(); if (!valid) { break; } } try { watcher.close(); } catch (IOException e) { e.printStackTrace(); } }
Example 5
Source File: FileWatcher.java From rest-utils with Apache License 2.0 | 5 votes |
private void handleNextWatchNotification() throws InterruptedException { log.debug("Watching file change: " + file); // wait for key to be signalled WatchKey key = watchService.take(); log.info("Watch Key notified"); for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { log.debug("Watch event is OVERFLOW"); continue; } WatchEvent<Path> ev = (WatchEvent<Path>)event; Path changed = this.file.getParent().resolve(ev.context()); log.info("Watch file change: " + ev.context() + "=>" + changed); // Need to use path equals than isSameFile if (Files.exists(changed) && changed.equals(this.file)) { log.debug("Watch matching file: " + file); try { callback.run(); } catch (Exception e) { log.warn("Hit error callback on file change", e); } break; } } key.reset(); }
Example 6
Source File: FileSystemWatcher.java From sldeditor with GNU General Public License v3.0 | 5 votes |
/** * Process watch events. * * @param key the key * @param keys the keys */ private void processWatchEvents(WatchKey key, List<WatchEvent<?>> keys) { for (WatchEvent<?> watchEvent : keys) { Kind<?> watchEventKind = watchEvent.kind(); // Sometimes events are created faster than they are registered // or the implementation may specify a maximum number of events // and further events are discarded. In these cases an event of // kind overflow is returned. We ignore this case for now if (watchEventKind == StandardWatchEventKinds.OVERFLOW) { continue; } Path dir = (Path) key.watchable(); Path fullPath = dir.resolve((Path) watchEvent.context()); FileWatcherUpdateInterface parentObj = watcherMap.get(key); if (parentObj != null) { if (watchEventKind == StandardWatchEventKinds.ENTRY_CREATE) { // A new file has been created parentObj.fileAdded(fullPath); } else if (watchEventKind == StandardWatchEventKinds.ENTRY_MODIFY) { ReloadManager.getInstance().fileModified(fullPath); // The file has been modified. parentObj.fileModified(fullPath); } else if (watchEventKind == StandardWatchEventKinds.ENTRY_DELETE) { parentObj.fileDeleted(fullPath); } } } }
Example 7
Source File: SVMJVMImpl.java From visualvm with GNU General Public License v2.0 | 5 votes |
private Path findHeapDumpFile(WatchKey key) { for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } WatchEvent<Path> ev = (WatchEvent<Path>)event; Path filename = ev.context(); String name = filename.toString(); if (name.endsWith(SVM_HEAP_DUMP_SUFFIX) && name.startsWith(SVM_HEAP_DUMP_PREFIX)) { return filename; } } return null; }
Example 8
Source File: FileSystemWatcher.java From meghanada-server with GNU General Public License v3.0 | 5 votes |
private static void handleEvent(final WatchKeyHolder watchKeys, final WatchKey key) throws IOException { for (final WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.OVERFLOW) { continue; } final WatchEvent<Path> watchEvent = cast(event); Path path = watchKeys.get(key); if (path == null) { continue; } path = path.resolve(watchEvent.context()); if (Files.isDirectory(path, LinkOption.NOFOLLOW_LINKS)) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) { watchKeys.register(path); } } else { // Dispatch FileEvent fe = toEvent(watchEvent, path); if (fe != null) { Executor.getInstance().getEventBus().post(fe); } } } }
Example 9
Source File: BeatmapWatchService.java From opsu-dance with GNU General Public License v3.0 | 4 votes |
/** * Process all events for keys queued to the watcher */ private void processEvents() { while (true) { // wait for key to be signaled WatchKey key; try { key = watcher.take(); } catch (InterruptedException | ClosedWatchServiceException e) { return; } Path dir = keys.get(key); if (dir == null) continue; boolean isPaused = paused; for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) continue; // context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); //System.out.printf("%s: %s\n", kind.name(), child); // fire listeners if (!isPaused) { for (BeatmapWatchServiceListener listener : listeners) listener.eventReceived(kind, child); } // if directory is created, then register it and its sub-directories if (kind == StandardWatchEventKinds.ENTRY_CREATE) { if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) registerAll(child); } } // reset key and remove from set if directory no longer accessible if (!key.reset()) { keys.remove(key); if (keys.isEmpty()) break; // all directories are inaccessible } } }
Example 10
Source File: NarAutoLoaderTask.java From nifi with Apache License 2.0 | 4 votes |
@Override public void run() { while (!stopped) { try { WatchKey key; try { LOGGER.debug("Polling for new NARs at {}", new Object[]{autoLoadPath}); key = watchService.poll(pollIntervalMillis, TimeUnit.MILLISECONDS); } catch (InterruptedException x) { LOGGER.info("WatchService interrupted, returning..."); return; } // Key comes back as null when there are no new create events, but we still want to continue processing // so we can consider files added to the candidateNars list in previous iterations if (key != null) { for (WatchEvent<?> event : key.pollEvents()) { final WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } final WatchEvent<Path> ev = (WatchEvent<Path>) event; final Path filename = ev.context(); final Path autoLoadFile = autoLoadPath.resolve(filename); final String autoLoadFilename = autoLoadFile.toFile().getName().toLowerCase(); if (!autoLoadFilename.endsWith(".nar")) { LOGGER.info("Skipping non-nar file {}", new Object[]{autoLoadFilename}); continue; } if (autoLoadFilename.startsWith(".")) { LOGGER.debug("Skipping partially written file {}", new Object[]{autoLoadFilename}); continue; } LOGGER.info("Found {} in auto-load directory", new Object[]{autoLoadFile}); candidateNars.add(autoLoadFile.toFile()); } final boolean valid = key.reset(); if (!valid) { LOGGER.error("NAR auto-load directory is no longer valid"); stop(); } } // Make sure that the created file is done being written by checking the last modified date of the file and // make sure a certain amount of time has passed indicating it is done being written to final List<File> readyNars = new ArrayList<>(); final Iterator<File> candidateNarIter = candidateNars.iterator(); while (candidateNarIter.hasNext()) { final File candidateNar = candidateNarIter.next(); final long fileAge = System.currentTimeMillis() - candidateNar.lastModified(); if (fileAge >= MIN_FILE_AGE) { readyNars.add(candidateNar); candidateNarIter.remove(); } else { LOGGER.debug("Candidate NAR {} not ready yet, will check again next time", new Object[]{candidateNar.getName()}); } } if (!readyNars.isEmpty()) { narLoader.load(readyNars); } } catch (final Exception e) { LOGGER.error("Error loading NARs due to: " + e.getMessage(), e); } } }
Example 11
Source File: FileMonitorConfiguration.java From spring-cloud-config with Apache License 2.0 | 4 votes |
private Set<File> filesFromEvents() { Set<File> files = new LinkedHashSet<File>(); if (this.watcher == null) { return files; } WatchKey key = this.watcher.poll(); while (key != null) { for (WatchEvent<?> event : key.pollEvents()) { if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE || event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) { Path item = (Path) event.context(); File file = new File(((Path) key.watchable()).toAbsolutePath() + File.separator + item.getFileName()); if (file.isDirectory()) { files.addAll(walkDirectory(file.toPath())); } else { if (!file.getPath().contains(".git") && !PatternMatchUtils .simpleMatch(this.excludes, file.getName())) { if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": " + file); } files.add(file); } } } else if (event.kind() == StandardWatchEventKinds.OVERFLOW) { if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } if (event.context() != null && event.context() instanceof Path) { files.addAll(walkDirectory((Path) event.context())); } else { for (Path path : this.directory) { files.addAll(walkDirectory(path)); } } } else { if (log.isDebugEnabled()) { log.debug("Watch Event: " + event.kind() + ": context: " + event.context()); } } } key.reset(); key = this.watcher.poll(); } return files; }
Example 12
Source File: FileSystemAssetWatcher.java From seventh with GNU General Public License v2.0 | 4 votes |
/** * @param dir * @throws IOException */ public FileSystemAssetWatcher(File dir) throws IOException { FileSystem fileSystem = FileSystems.getDefault(); this.isActive = new AtomicBoolean(false); this.watchedAssets = new ConcurrentHashMap<File, WatchedAsset<?>>(); this.pathToWatch = dir.toPath(); this.watchService = fileSystem.newWatchService(); this.watchThread = new Thread(new Runnable() { @SuppressWarnings("unchecked") @Override public void run() { while(isActive.get()) { try { WatchKey key = watchService.take(); if(key.isValid()) { List<WatchEvent<?>> events = key.pollEvents(); for(int i = 0; i < events.size(); i++) { WatchEvent<?> event = events.get(i); WatchEvent.Kind<?> kind = event.kind(); /* ignore overflow events */ if(kind == StandardWatchEventKinds.OVERFLOW) { continue; } /* we are only listening for 'changed' events */ WatchEvent<Path> ev = (WatchEvent<Path>)event; Path filename = ev.context(); /* if we have a registered asset, lets go ahead and notify it */ WatchedAsset<?> watchedAsset = watchedAssets.get(new File(pathToWatch.toFile(), filename.toString())); if(watchedAsset != null) { try { watchedAsset.onAssetChanged(); } catch (IOException e) { e.printStackTrace(); } } } } key.reset(); } catch (ClosedWatchServiceException e) { break; } catch (InterruptedException e) { break; } } } }, "watcher-thread"); this.watchThread.setDaemon(true); this.pathToWatch.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY); }
Example 13
Source File: VideoCaptureWatcher.java From Java-Coding-Problems with MIT License | 4 votes |
public void watchVideoCaptureSystem(Path path) throws IOException, InterruptedException { try (WatchService watchService = FileSystems.getDefault().newWatchService()) { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE); System.out.println("Watching captures ..."); //start an infinite loop while (true) { //retrieve and remove the next watch key final WatchKey key = watchService.poll(11, TimeUnit.SECONDS); if (key == null) { throw new IllegalStateException("The video capture system is jammed. Missed capture!"); } //get list of 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; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); final Path child = path.resolve(filename); if (Files.probeContentType(child).equals("image/jpeg")) { //print it out the video capture time SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss"); System.out.println("Video capture successfully at: " + dateFormat.format(new Date())); } else { Files.deleteIfExists(child); throw new IllegalStateException("Unauthorized file type has been added!"); } } //reset the key boolean valid = key.reset(); //exit loop if the key is not valid (if the directory was deleted, per example) if (!valid) { break; } } } } }
Example 14
Source File: PollingWatchService.java From openjdk-jdk9 with GNU General Public License v2.0 | 4 votes |
/** * Register the given file with this watch service */ @Override WatchKey register(final Path path, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers) throws IOException { // check events - CCE will be thrown if there are invalid elements final Set<WatchEvent.Kind<?>> eventSet = new HashSet<>(events.length); for (WatchEvent.Kind<?> event: events) { // standard events if (event == StandardWatchEventKinds.ENTRY_CREATE || event == StandardWatchEventKinds.ENTRY_MODIFY || event == StandardWatchEventKinds.ENTRY_DELETE) { eventSet.add(event); continue; } // OVERFLOW is ignored if (event == StandardWatchEventKinds.OVERFLOW) { continue; } // null/unsupported if (event == null) throw new NullPointerException("An element in event set is 'null'"); throw new UnsupportedOperationException(event.name()); } if (eventSet.isEmpty()) throw new IllegalArgumentException("No events to register"); // Extended modifiers may be used to specify the sensitivity level int sensitivity = 10; if (modifiers.length > 0) { for (WatchEvent.Modifier modifier: modifiers) { if (modifier == null) throw new NullPointerException(); if (ExtendedOptions.SENSITIVITY_HIGH.matches(modifier)) { sensitivity = ExtendedOptions.SENSITIVITY_HIGH.parameter(); } else if (ExtendedOptions.SENSITIVITY_MEDIUM.matches(modifier)) { sensitivity = ExtendedOptions.SENSITIVITY_MEDIUM.parameter(); } else if (ExtendedOptions.SENSITIVITY_LOW.matches(modifier)) { sensitivity = ExtendedOptions.SENSITIVITY_LOW.parameter(); } else { throw new UnsupportedOperationException("Modifier not supported"); } } } // check if watch service is closed if (!isOpen()) throw new ClosedWatchServiceException(); // registration is done in privileged block as it requires the // attributes of the entries in the directory. try { int value = sensitivity; return AccessController.doPrivileged( new PrivilegedExceptionAction<PollingWatchKey>() { @Override public PollingWatchKey run() throws IOException { return doPrivilegedRegister(path, eventSet, value); } }); } catch (PrivilegedActionException pae) { Throwable cause = pae.getCause(); if (cause != null && cause instanceof IOException) throw (IOException)cause; throw new AssertionError(pae); } }
Example 15
Source File: MainPanel.java From java-swing-tips with MIT License | 4 votes |
public void processEvents(Path dir, WatchService watcher) { for (;;) { // wait for key to be signaled WatchKey key; try { key = watcher.take(); } catch (InterruptedException ex) { EventQueue.invokeLater(() -> append("Interrupted")); Thread.currentThread().interrupt(); return; } for (WatchEvent<?> event: key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); // This key is registered only for ENTRY_CREATE events, // but an OVERFLOW event can occur regardless if events // are lost or discarded. if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } // The filename is the context of the event. @SuppressWarnings("unchecked") WatchEvent<Path> ev = (WatchEvent<Path>) event; Path filename = ev.context(); Path child = dir.resolve(filename); EventQueue.invokeLater(() -> { append(String.format("%s: %s", kind, child)); updateTable(kind, child); }); } // Reset the key -- this step is critical if you want to // receive further watch events. If the key is no longer valid, // the directory is inaccessible so exit the loop. boolean valid = key.reset(); if (!valid) { break; } } }
Example 16
Source File: BeatmapWatchService.java From opsu with GNU General Public License v3.0 | 4 votes |
/** * Process all events for keys queued to the watcher */ private void processEvents() { while (true) { // wait for key to be signaled WatchKey key; try { key = watcher.take(); } catch (InterruptedException | ClosedWatchServiceException e) { return; } Path dir = keys.get(key); if (dir == null) continue; boolean isPaused = paused; for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW) continue; // context for directory entry event is the file name of entry WatchEvent<Path> ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); //System.out.printf("%s: %s\n", kind.name(), child); // fire listeners if (!isPaused) { for (BeatmapWatchServiceListener listener : listeners) listener.eventReceived(kind, child); } // if directory is created, then register it and its sub-directories if (kind == StandardWatchEventKinds.ENTRY_CREATE) { if (Files.isDirectory(child, LinkOption.NOFOLLOW_LINKS)) registerAll(child); } } // reset key and remove from set if directory no longer accessible if (!key.reset()) { keys.remove(key); if (keys.isEmpty()) break; // all directories are inaccessible } } }
Example 17
Source File: DirWatcher.java From Jupiter with GNU General Public License v3.0 | 4 votes |
/** {@inheritDoc} */ @Override public Void call() { registerAll(FS.toPath(Settings.USER_DIR.get())); while(!isCancelled()) { // wait for key to be signalled WatchKey key; try { key = watcher.take(); } catch (InterruptedException e) { break; } // get path Path dir = keys.get(key); // ignore unregistered keys if (dir == null) { continue; } // get events for (WatchEvent<?> event : key.pollEvents()) { WatchEvent.Kind kind = event.kind(); // ignore overflow events if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } @SuppressWarnings("unchecked") File file = dir.resolve(((WatchEvent<Path>) event).context()).toFile(); // handle event if (kind == StandardWatchEventKinds.ENTRY_CREATE && file.isDirectory()) { pcs.firePropertyChange("create_dir", "create", file); // register new keys registerAll(file.toPath()); } else if (kind == StandardWatchEventKinds.ENTRY_CREATE) { pcs.firePropertyChange("create_file", "create", file); } else if (kind == StandardWatchEventKinds.ENTRY_DELETE && file.isDirectory()) { pcs.firePropertyChange("delete_dir", "delete", file); } else if (kind == StandardWatchEventKinds.ENTRY_DELETE) { pcs.firePropertyChange("delete_file", "delete", file); } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY && file.isDirectory()) { pcs.firePropertyChange("modify_dir", "modify", file); } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) { pcs.firePropertyChange("modify_file", "modify", file); } } boolean valid = key.reset(); if (!valid) { keys.remove(key); if (keys.isEmpty()) { break; } } } return null; }
Example 18
Source File: DFFileMonitor.java From dfactor with MIT License | 4 votes |
@Override public void run() { _onLoop = true; _registAll(Paths.get(dirRoot.getAbsolutePath())); WatchKey key = null; while(_onLoop){ // 获取下一个文件改动事件 try { key = watcher.poll(2000, TimeUnit.MILLISECONDS); } catch (InterruptedException e) { e.printStackTrace(); continue; } if(key == null){ continue; } Path dir = _mapKeyPath.get(key); if(dir == null){ continue; } for (WatchEvent<?> event : key.pollEvents()) { Kind<?> kind = event.kind(); // 事件可能丢失或遗弃 if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } WatchEvent<Path> ev = (WatchEvent<Path>) event; Path name = ev.context(); Path child = dir.resolve(name); File file = child.toFile(); if(kind.name().equals(StandardWatchEventKinds.ENTRY_CREATE.name())){ // print("create: " + file +" --> " + event.kind()); if(file.isDirectory()){ _regist(Paths.get(file.getAbsolutePath()), watcher); } listener.onCreate(file); }else if(kind.name().equals(StandardWatchEventKinds.ENTRY_DELETE.name())){ // print("delete: " + file +" --> " + event.kind()); listener.onDelete(file); }else if(kind.name().equals(StandardWatchEventKinds.ENTRY_MODIFY.name())){ // print("modify: " + file +" --> " + event.kind()); listener.onModify(file); } } // 重设WatchKey boolean valid = key.reset(); // 如果重设失败,退出监听 if (!valid) { // 移除不可访问的目录 // 因为有可能目录被移除,就会无法访问 _mapKeyPath.remove(key); // 如果待监控的目录都不存在了,就中断执行 if (_mapKeyPath.isEmpty()) { break; } } } listener.onClose(); }
Example 19
Source File: FolderWatcher.java From Java-Coding-Problems with MIT License | 4 votes |
public void watchFolder(Path path) throws IOException, InterruptedException { try (WatchService watchService = FileSystems.getDefault().newWatchService()) { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); System.out.println("Watching: " + path); //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, per example) if (!valid) { break; } } } }
Example 20
Source File: PrinterTrayWatcher.java From Java-Coding-Problems with MIT License | 4 votes |
public void watchTray(Path path) throws IOException, InterruptedException { try (WatchService watchService = FileSystems.getDefault().newWatchService()) { path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE); System.out.println("Printer watcher ready ..."); //start an infinite loop while (true) { //retrieve and remove the next watch key final WatchKey key = watchService.poll(10, TimeUnit.SECONDS); //get list of events for the watch key if (key != null) { for (WatchEvent<?> watchEvent : key.pollEvents()) { //get the filename for the event final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent; final Path filename = watchEventPath.context(); //get the kind of event (create, modify, delete) final Kind<?> kind = watchEvent.kind(); //handle OVERFLOW event if (kind == StandardWatchEventKinds.OVERFLOW) { continue; } if (kind == StandardWatchEventKinds.ENTRY_CREATE) { System.out.println("Sending the document to print -> " + filename); Runnable task = new Printer(path.resolve(filename)); Thread worker = new Thread(task); //we can set the name of the thread worker.setName(path.resolve(filename).toString()); //store the thread and the path threads.put(worker, path.resolve(filename)); //start the thread worker.start(); } if (kind == StandardWatchEventKinds.ENTRY_DELETE) { System.out.println(filename + " was successfully printed!"); } } //reset the key boolean valid = key.reset(); //exit loop if the key is not valid (if the directory was deleted, per example) if (!valid) { threads.clear(); break; } } if (!threads.isEmpty()) { for (Iterator<Map.Entry<Thread, Path>> it = threads.entrySet().iterator(); it.hasNext();) { Map.Entry<Thread, Path> entry = it.next(); if (entry.getKey().getState() == Thread.State.TERMINATED) { Files.deleteIfExists(entry.getValue()); it.remove(); } } } } } }