Java Code Examples for java.nio.file.WatchKey

Following code examples demonstrate how to use java.nio.file.WatchKeyfrom java. These examples are extracted from various highly rated open source projects. You can directly use these code snippets or view their entire linked source code. These snippets are extracted to provide contextual information about how to use this class in the real world. These samples also let you understand some good practices on how to use java.nio.file.WatchKeyand various code implementation of this class.

    public DirBeingWatched(WatchKey key, Path path) {
        this.key = key;
        this.path = path;
    } 


	public static void main(String[] args) {
		boolean shutdown=false;
		try {
			WatchService watcher=FileSystems.getDefault().newWatchService();
			Path path=FileSystems.getDefault().getPath(".");
			WatchKey key=path.register(watcher,StandardWatchEventKinds.ENTRY_MODIFY);
			while(!shutdown){
				key=watcher.take();
				for(WatchEvent<?> event:key.pollEvents()){
					if(event.kind()==StandardWatchEventKinds.ENTRY_MODIFY){
						System.out.println("data1 is modified");
					}
				}
				key.reset();
			}
		} catch (IOException | InterruptedException e) {
			e.printStackTrace();
		}
		
	} 

    @Test
    public default void verifyGenericType()
    throws Exception {
        final Class<SUT> sut = createNewSUT();
        assertTrue("This j8unit test interface is used with a generic type that is illegaly not assignable to WatchKey.class!",
                   WatchKey.class.isAssignableFrom(sut));
    } 

    @Override
    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>... events)
            throws IOException {
        return new NopWatchKey();
    } 

    @Override
    public WatchKey register(WatchService watcher, WatchEvent.Kind<?>[] events,
                             WatchEvent.Modifier... modifiers)
            throws IOException {
        return new NopWatchKey();
    } 

	public static void main(String[] args) throws Exception {
		
		final File parentFile = new File("/Users/power/Tmp");
		final WatchService wService = FileSystems.getDefault().newWatchService();
		
		{		
			WatchKey register = parentFile.toPath().register(wService, ENTRY_CREATE);
			System.err.println(register);
		}
	
		{
			WatchKey register = parentFile.toPath().register(wService, ENTRY_CREATE);
			System.err.println(register);
		}
				
		wService.close();
	} 

      synchronized (MacOSXWatchKey.this) {
        final int overflowCount = overflow.getAndSet(0);
        final List<WatchEvent<?>> result =
            new ArrayList<>(events.size() + overflowCount > 0 ? 1 : 0);
        events.drainTo(result);
        if (overflowCount != 0) {
          result.add(new Event<>(OVERFLOW, overflowCount, watchable));
        }
        return Collections.unmodifiableList(result);
      } 

    void addEvent(Event<Path> event) {
      synchronized (MacOSXWatchKey.this) {
        if (!events.offer(event)) {
          overflow.incrementAndGet();
        } else {
          if (!readyKeys.contains(this)) {
            readyKeys.add(this);
          }
        }
      }
    } 

    @Override
    public void startWatching() throws IOException
    {
        logger.entering(FileSystemWatcher.class.getName(), "startWatching");
        try (WatchService watcher = FileSystems.getDefault().newWatchService())
        {
            Set<WatchKey> keys = new HashSet<>();
            for (Path directory : directories)
            {
                logger.log(Level.FINEST, "Watching directory:{0}", directory.toString());
                WatchKey key = directory.register(watcher, ENTRY_MODIFY);
                keys.add(key);
            }
            boolean keepGoing = true;
            logger.log(Level.FINEST, "Entering while-loop.");
            while (keepGoing)
            {
                WatchKey foundKey;
                try
                {
                    foundKey = watcher.take();
                } catch (InterruptedException ex)
                {
                    logger.log(Level.INFO, null, ex);
                    continue;
                }
                List<WatchEvent<?>> events = foundKey.pollEvents();
                for (WatchEvent<?> event : events)
                {
                    processEvent(event);
                }
                keepGoing = foundKey.reset();
            }
            for (WatchKey key : keys)
            {
                key.cancel();
            }

        }
        logger.exiting(FileSystemWatcher.class.getName(), "startWatching");
    } 

    @Override
    public WatchKey take()
            throws InterruptedException {
        return null;
    } 

    @Override
    public WatchKey poll(final long timeout, final TimeUnit unit)
            throws InterruptedException {
        unit.sleep(timeout);
        return null;
    } 

  public static void main(String[] args) {

    try {
      WatchService watcher = FileSystems.getDefault().newWatchService();

      Path dir = FileSystems.getDefault().getPath("/usr/karianna");

      WatchKey key = dir.register(watcher, ENTRY_MODIFY);

      while (!shutdown) {
        key = watcher.take();
        for (WatchEvent<?> event : key.pollEvents()) {
          if (event.kind() == ENTRY_MODIFY) {
            System.out.println("Home dir changed!");
          }
        }
        key.reset();
      }
    } catch (IOException | InterruptedException e) {
      System.out.println(e.getMessage());
    }
  } 

    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();
                if (kind == StandardWatchEventKinds.OVERFLOW) continue;
                System.out.format("%s: %s\n", kind.name(), cast(event).context());
            }
            key.reset();
        }
    } 

	public static void main(String[] args) {
		try {
			WatchService watchService = FileSystems.getDefault().newWatchService();
			WatchKey watchKey = watchService.take();
		} catch (IOException e) {
			e.printStackTrace();
		} catch (Exception e) {
			e.printStackTrace();
		}
	} 

Advertisement
Javadoc
A token representing the registration of a Watchable watchable object with a WatchService.
r> A watch key is created when a watchable object is registered with a watch service. The key remains #isValid valid until: It is cancelled, explicitly, by invoking its #cancel cancel method, or Cancelled implicitly, because the object is no longer accessible, or By WatchService#close closing the watch service.

A watch key has a state. When initially created the key is said to be ready. When an event is detected then the key is signalled and queued so that it can be retrieved by invoking the watch service's WatchService#poll() poll or WatchService#take() take methods. Once signalled, a key remains in this state until its #reset reset method is invoked to return the key to the ready state. Events detected while the key is in the signalled state are queued but do not cause the key to be re-queued for retrieval from the watch service. Events are retrieved by invoking the key's #pollEvents pollEvents method. This method retrieves and removes all events accumulated for the object. When initially created, a watch key has no pending events. Typically events are retrieved when the key is in the signalled state leading to the following idiom: for (;;) { // retrieve key WatchKey key = watcher.take(); // process events for (WatchEvent<?> event: key.pollEvents()) { : // reset the key boolean valid = key.reset(); if (!valid) { // object no longer registered

Watch keys are safe for use by multiple concurrent threads. Where there are several threads retrieving signalled keys from a watch service then care should be taken to ensure that the reset method is only invoked after the events for the object have been processed. This ensures that one thread is processing the events for an object at any time. @since 1.7

Read More
Advertisement