Java Code Examples for java.nio.file.WatchEvent.Kind

The following examples show how to use java.nio.file.WatchEvent.Kind. These examples are extracted from open source projects. 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 Project: PeonyFramwork   Source File: ResourceListener.java    License: Apache License 2.0 6 votes vote down vote up
public static void main(String[] args) throws IOException {
	FileListener listener = new FileListener() {
		@Override
		public void onEvent(String rootPath, WatchEvent<Path> event) {
			Kind<Path> kind = event.kind();
			String fileName = event.context().getFileName().toString();
			if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
				System.err.println(rootPath +"/"+fileName +"   "+ event.kind().name());
			}
		}

		@Override
		public Kind<?>[] events() {
			return new Kind<?>[] { StandardWatchEventKinds.ENTRY_MODIFY };
		}
	};

	ResourceListener.addListener("E:/jPersist2", listener);
	ResourceListener.addListener("E:/MyDownloads/Download", listener);
}
 
Example 2
@Override
public void handleFileChanged(Kind<?> operation, String fileAbsolutePathname) {
	if (StandardWatchEventKinds.ENTRY_CREATE.equals(operation)) {
		DecryptedFile recentlyRemovedEntry = recentlyRemoved.getIfPresent(fileAbsolutePathname);
		if (recentlyRemovedEntry != null) {
			addOrUpdate(recentlyRemovedEntry);
		}
		return;
	}

	if (StandardWatchEventKinds.ENTRY_DELETE.equals(operation)) {
		remove(fileAbsolutePathname);
		return;
	}

	// Other cases not supported -- not needed
}
 
Example 3
Source Project: openhab-core   Source File: WatchQueueReader.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void registerWithSubDirectories(AbstractWatchService watchService, Path toWatch) throws IOException {
    Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs)
                        throws IOException {
                    Kind<?>[] kinds = watchService.getWatchEventKinds(subDir);
                    if (kinds != null) {
                        registerDirectoryInternal(watchService, kinds, subDir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    if (exc instanceof AccessDeniedException) {
                        logger.warn("Access to folder '{}' was denied, therefore skipping it.",
                                file.toAbsolutePath().toString());
                    }
                    return FileVisitResult.SKIP_SUBTREE;
                }
            });
}
 
Example 4
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
        File f = path.toFile();
        if (!f.isHidden() && f.getName().endsWith(".cfg")) {
            configDispatcher.processConfigFile(f);
        }
    } else if (kind == ENTRY_DELETE) {
        // Detect if a service specific configuration file was removed. We want to
        // notify the service in this case with an updated empty configuration.
        File configFile = path.toFile();
        if (configFile.isHidden() || configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
            return;
        }
        configDispatcher.fileRemoved(configFile.getAbsolutePath());
    }
}
 
Example 5
Source Project: openhab-core   Source File: ScriptFileWatcher.java    License: Eclipse Public License 2.0 6 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File file = path.toFile();
    if (!file.isHidden()) {
        try {
            URL fileUrl = file.toURI().toURL();
            if (ENTRY_DELETE.equals(kind)) {
                removeFile(fileUrl);
            }

            if (file.canRead() && (ENTRY_CREATE.equals(kind) || ENTRY_MODIFY.equals(kind))) {
                importFile(fileUrl);
            }
        } catch (MalformedURLException e) {
            logger.error("malformed", e);
        }
    }
}
 
Example 6
private void fullEventAssertionsByKind(String fileName, Kind<?> kind, boolean osSpecific) throws Exception {
    waitForAssert(() -> assertThat(watchService.allFullEvents.size() >= 1, is(true)), DFL_TIMEOUT * 2,
            DFL_SLEEP_TIME);

    if (osSpecific && ENTRY_DELETE.equals(kind)) {
        // There is possibility that one more modify event is triggered on some OS
        // so sleep a bit extra time
        Thread.sleep(500);
        cleanUpOsSpecificModifyEvent();
    }

    assertEventCount(1);
    FullEvent fullEvent = watchService.allFullEvents.get(0);

    assertThat(fullEvent.eventPath.toString(), is(WATCHED_DIRECTORY + File.separatorChar + fileName));
    assertThat(fullEvent.eventKind, is(kind));
    assertThat(fullEvent.watchEvent.count() >= 1, is(true));
    assertThat(fullEvent.watchEvent.kind(), is(fullEvent.eventKind));
    String fileNameOnly = fileName.contains(File.separatorChar + "")
            ? fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1, fileName.length())
            : fileName;
    assertThat(fullEvent.watchEvent.context().toString(), is(fileNameOnly));

    // Clear all the asserted events
    watchService.allFullEvents.clear();
}
 
Example 7
Source Project: LiveDirsFX   Source File: LiveDirs.java    License: BSD 2-Clause "Simplified" License 6 votes vote down vote up
private void processEvent(Path dir, WatchEvent<Path> event) {
    // Context for directory entry event is the file name of entry
    Path relChild = event.context();
    Path child = dir.resolve(relChild);

    Kind<Path> kind = event.kind();

    if(kind == ENTRY_MODIFY) {
        handleModification(child, externalInitiator);
    } else if(kind == ENTRY_CREATE) {
        handleCreation(child, externalInitiator);
    } else if(kind == ENTRY_DELETE) {
        model.delete(child, externalInitiator);
    } else {
        throw new AssertionError("unreachable code");
    }
}
 
Example 8
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    if (kind == ENTRY_CREATE || kind == ENTRY_MODIFY) {
        File f = path.toFile();
        if (!f.isHidden() && f.getName().endsWith(".cfg")) {
            configDispatcher.processConfigFile(f);
        }
    } else if (kind == ENTRY_DELETE) {
        // Detect if a service specific configuration file was removed. We want to
        // notify the service in this case with an updated empty configuration.
        File configFile = path.toFile();
        if (configFile.isHidden() || configFile.isDirectory() || !configFile.getName().endsWith(".cfg")) {
            return;
        }
        configDispatcher.fileRemoved(configFile.getAbsolutePath());
    }
}
 
Example 9
private void fullEventAssertionsByKind(String fileName, Kind<?> kind, boolean osSpecific) throws Exception {
    waitForAssert(() -> assertThat(watchService.allFullEvents.size() >= 1, is(true)), DFL_TIMEOUT * 2,
            DFL_SLEEP_TIME);

    if (osSpecific && kind.equals(ENTRY_DELETE)) {
        // There is possibility that one more modify event is triggered on some OS
        // so sleep a bit extra time
        Thread.sleep(500);
        cleanUpOsSpecificModifyEvent();
    }

    assertEventCount(1);
    FullEvent fullEvent = watchService.allFullEvents.get(0);

    assertThat(fullEvent.eventPath.toString(), is(WATCHED_DIRECTORY + File.separatorChar + fileName));
    assertThat(fullEvent.eventKind, is(kind));
    assertThat(fullEvent.watchEvent.count() >= 1, is(true));
    assertThat(fullEvent.watchEvent.kind(), is(fullEvent.eventKind));
    String fileNameOnly = fileName.contains(File.separatorChar + "")
            ? fileName.substring(fileName.lastIndexOf(File.separatorChar) + 1, fileName.length())
            : fileName;
    assertThat(fullEvent.watchEvent.context().toString(), is(fileNameOnly));

    // Clear all the asserted events
    watchService.allFullEvents.clear();
}
 
Example 10
Source Project: smarthome   Source File: WatchQueueReader.java    License: Eclipse Public License 2.0 6 votes vote down vote up
private void registerWithSubDirectories(AbstractWatchService watchService, Path toWatch) throws IOException {
    Files.walkFileTree(toWatch, EnumSet.of(FileVisitOption.FOLLOW_LINKS), Integer.MAX_VALUE,
            new SimpleFileVisitor<Path>() {
                @Override
                public FileVisitResult preVisitDirectory(Path subDir, BasicFileAttributes attrs)
                        throws IOException {
                    Kind<?>[] kinds = watchService.getWatchEventKinds(subDir);
                    if (kinds != null) {
                        registerDirectoryInternal(watchService, kinds, subDir);
                    }
                    return FileVisitResult.CONTINUE;
                }

                @Override
                public FileVisitResult visitFileFailed(Path file, IOException exc) throws IOException {
                    if (exc instanceof AccessDeniedException) {
                        logger.warn("Access to folder '{}' was denied, therefore skipping it.",
                                file.toAbsolutePath().toString());
                    }
                    return FileVisitResult.SKIP_SUBTREE;
                }
            });
}
 
Example 11
@SuppressWarnings("unchecked")
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    logger.debug("New watch event {} for path {}.", kind, path);

    if (kind == OVERFLOW) {
        return;
    }

    final WatchEvent<Path> ev = (WatchEvent<Path>) event;
    final Path filename = ev.context();

    logger.debug("Reloading javascript file {}.", filename);

    manager.removeFromCache(filename.toString());
}
 
Example 12
Source Project: PeerWasp   Source File: FolderWatchService.java    License: MIT License 6 votes vote down vote up
/**
 * Precondition: Event and child must not be null.
 * @param kind type of the event (create, modify, ...)
 * @param source Identifies the related file.
 */
private void handleEvent(Kind<Path> kind, Path source) {
	try {
		if(PathUtils.isFileHidden(source)){
			return;
		}
		if (kind.equals(ENTRY_CREATE)) {
			addNotifyEvent(new NotifyFileCreated(source));
		} else if (kind.equals(ENTRY_MODIFY)) {
			addNotifyEvent(new NotifyFileModified(source));
		} else if (kind.equals(ENTRY_DELETE)) {
			addNotifyEvent(new NotifyFileDeleted(source));
		} else if (kind.equals(OVERFLOW)) {
			// error - overflow... should not happen here (continue if such an event occurs).
			// handled already
			logger.warn("Overflow event from watch service. Too many events?");
		} else {
			logger.warn("Unknown event received");
		}
	} catch (InterruptedException iex) {
		// put into queue failed
		logger.info("Handling event interrupted.", iex);
	}
}
 
Example 13
Source Project: Launcher   Source File: DirWatcher.java    License: GNU General Public License v3.0 5 votes vote down vote up
private void processKey(WatchKey key) throws IOException {
    Path watchDir = (Path) key.watchable();
    for (WatchEvent<?> event : key.pollEvents()) {
        Kind<?> kind = event.kind();
        if (kind.equals(StandardWatchEventKinds.OVERFLOW)) {
            if (PROP_IGN_OVERFLOW)
                continue; // Sometimes it's better to ignore than interrupt fair playing
            throw new IOException("Overflow");
        }

        // Resolve paths and verify is not exclusion
        Path path = watchDir.resolve((Path) event.context());
        Deque<String> stringPath = toPath(dir.relativize(path));
        if (matcher != null && !matcher.shouldVerify(stringPath))
            continue; // Exclusion; should not be verified
        // Verify is REALLY modified (not just attributes)
        if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
            HashedEntry entry = hdir.resolve(stringPath);
            if (entry != null && (entry.getType() != HashedEntry.Type.FILE || ((HashedFile) entry).isSame(path, digest)))
                continue; // Modified attributes, not need to worry :D
        }

        // Forbidden modification!
        throw new SecurityException(String.format("Forbidden modification (%s, %d times): '%s'", kind, event.count(), path));
    }
    key.reset();
}
 
Example 14
Source Project: directory-watcher   Source File: AbstractWatchKey.java    License: Apache License 2.0 5 votes vote down vote up
public AbstractWatchKey(
    AbstractWatchService watcher,
    Watchable watchable,
    Iterable<? extends WatchEvent.Kind<?>> subscribedTypes,
    int queueSize) {
  this.watcher = requireNonNull(watcher);
  this.watchable = watchable; // nullable for Watcher poison
  this.events = new ArrayBlockingQueue<>(queueSize);

  Set<Kind<?>> types = new HashSet<Kind<?>>();
  subscribedTypes.forEach(types::add);
  this.subscribedTypes = Collections.unmodifiableSet(types);
}
 
Example 15
Source Project: baratine   Source File: JWatchService.java    License: GNU General Public License v2.0 5 votes vote down vote up
protected JWatchKey register(JPath path, Kind<?>[] events, Modifier ... modifiers)
{
  JWatchKey key = new JWatchKey(this, path, events, modifiers);

  synchronized (this) {
    _watchList.add(key);
  }

  return key;
}
 
Example 16
Source Project: baratine   Source File: JWatchKey.java    License: GNU General Public License v2.0 5 votes vote down vote up
public JWatchKey(JWatchService watchService,
                 JPath path,
                 Kind<?>[] events,
                 Modifier ... modifiers)
{
  Objects.requireNonNull(events);

  _watchService = watchService;
  _path = path;
  _events = events;
  _modifiers = modifiers;

  _watchHandle = path.getBfsFile().watch(pathString -> onWatch(pathString));
}
 
Example 17
Source Project: baratine   Source File: JPath.java    License: GNU General Public License v2.0 5 votes vote down vote up
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events,
                         Modifier... modifiers) throws IOException
{
  if (events.length == 0) {
    throw new IllegalArgumentException(L.l("no events specified to watch on: {0}", toUri()));
  }

  JWatchService jWatcher = (JWatchService) watcher;

  WatchKey key = jWatcher.register(this, events, modifiers);

  return key;
}
 
Example 18
Source Project: sldeditor   Source File: FileSystemWatcher.java    License: GNU General Public License v3.0 5 votes vote down vote up
/**
 * 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 19
Source Project: thorntail   Source File: Main.java    License: Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
private static void processEvents(File watchedDir, Path file) {
    for (;;) {

        WatchKey key;
        try {
            key = watcher.take();
        } catch (InterruptedException x) {
            return;
        }

        for (WatchEvent<?> event: key.pollEvents()) {
            Kind<?> kind = event.kind();

            WatchEvent<Path> ev = (WatchEvent<Path>)event;
            Path name = ev.context();
            Path child = watchedDir.toPath().resolve(name);

            if (kind == ENTRY_DELETE && child.equals(file)) {
                return;
            }
        }

        boolean valid = key.reset();
        if (!valid) {
           break;
        }
    }
}
 
Example 20
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File file = path.toFile();
    if (!file.isHidden()) {
        if (ENTRY_DELETE.equals(kind)) {
            provider.removeResources(file);
        } else if (file.canRead()) {
            provider.importResources(file);
        }
    }
}
 
Example 21
Source Project: openhab-core   Source File: FolderObserver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected Kind<?>[] getWatchEventKinds(Path directory) {
    if (directory != null && isNotEmpty(folderFileExtMap)) {
        String folderName = directory.getFileName().toString();
        if (folderFileExtMap.containsKey(folderName)) {
            return new Kind<?>[] { ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY };
        }
    }
    return null;
}
 
Example 22
Source Project: openhab-core   Source File: FolderObserver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File toCheck = getFileByFileExtMap(folderFileExtMap, path.getFileName().toString());
    if (toCheck != null && !toCheck.isHidden()) {
        checkFile(modelRepository, toCheck, kind);
    }
}
 
Example 23
Source Project: jsr203-hadoop   Source File: HadoopPath.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public WatchKey register(WatchService watcher, Kind<?>[] events,
    Modifier... modifiers) throws IOException {
  if (watcher == null || events == null || modifiers == null) {
    throw new NullPointerException();
  }

  // Not implemented now
  // The Hadoop API for notification is not stable
  throw new IOException("Not implemented");
}
 
Example 24
Source Project: buck   Source File: BuckUnixPath.java    License: Apache License 2.0 5 votes vote down vote up
@Override
public WatchKey register(
    WatchService watcher, WatchEvent.Kind<?>[] events, WatchEvent.Modifier... modifiers)
    throws IOException {
  // TODO(buck_team): do not recourse to default Path implementation
  return asDefault().register(watcher, events, modifiers);
}
 
Example 25
Source Project: smarthome   Source File: FolderObserver.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File toCheck = getFileByFileExtMap(folderFileExtMap, path.getFileName().toString());
    if (toCheck != null && !toCheck.isHidden()) {
        checkFile(modelRepo, toCheck, kind);
    }
}
 
Example 26
Source Project: smarthome   Source File: AutomationWatchService.java    License: Eclipse Public License 2.0 5 votes vote down vote up
@Override
protected void processWatchEvent(WatchEvent<?> event, Kind<?> kind, Path path) {
    File file = path.toFile();
    if (!file.isHidden()) {
        if (kind.equals(ENTRY_DELETE)) {
            provider.removeResources(file);
        } else if (file.canRead()) {
            provider.importResources(file);
        }
    }
}
 
Example 27
Source Project: jsch-nio   Source File: UnixSshPathWatchKey.java    License: MIT License 5 votes vote down vote up
public UnixSshPathWatchKey( UnixSshFileSystemWatchService watchService, UnixSshPath dir, Kind<?>[] kinds, long pollingInterval, TimeUnit pollingIntervalTimeUnit ) {
    this.watchService = watchService;
    this.dir = dir;
    this.kindsToWatch = new HashSet<>();
    this.kindsToWatch.addAll( Arrays.asList( kinds ) );
    this.pollingInterval = pollingInterval;
    this.pollingIntervalTimeUnit = pollingIntervalTimeUnit;
    this.cancelled = false;
    this.initialized = false;
    this.addMap = new HashMap<>();
    this.deleteMap = new HashMap<>();
    this.modifyMap = new HashMap<>();
    this.state = State.READY;
}
 
Example 28
Source Project: Java-Coding-Problems   Source File: VideoCaptureWatcher.java    License: MIT License 4 votes vote down vote up
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 29
Source Project: Java-Coding-Problems   Source File: PrinterTrayWatcher.java    License: MIT License 4 votes vote down vote up
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();
                    }
                }
            }
        }
    }
}
 
Example 30
Source Project: Java-Coding-Problems   Source File: FolderWatcher.java    License: MIT License 4 votes vote down vote up
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;
            }

        }
    }
}