当前位置: 首页>>代码示例>>Java>>正文


Java WatchKey类代码示例

本文整理汇总了Java中java.nio.file.WatchKey的典型用法代码示例。如果您正苦于以下问题:Java WatchKey类的具体用法?Java WatchKey怎么用?Java WatchKey使用的例子?那么, 这里精选的类代码示例或许可以为您提供帮助。


WatchKey类属于java.nio.file包,在下文中一共展示了WatchKey类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: watch

import java.nio.file.WatchKey; //导入依赖的package包/类
private void watch() {
    try {
        WatchService watchService = directoryPath.getFileSystem().newWatchService();
        directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
        while (true) {
            WatchKey watchKey = watchService.take();
            for (final WatchEvent<?> event : watchKey.pollEvents()) {
                takeActionOnChangeEvent(event);
            }
        }

    } catch (InterruptedException interruptedException) {
        System.out.println("Thread got interrupted:" + interruptedException);
    } catch (Exception exception) {
        exception.printStackTrace();
    }

}
 
开发者ID:patexoid,项目名称:ZombieLib2,代码行数:20,代码来源:DirWatcherService.java

示例2: watchDir

import java.nio.file.WatchKey; //导入依赖的package包/类
protected void watchDir(Path dir) throws IOException {
    LOG.debug("Registering watch for {}", dir);
    if (Thread.currentThread().isInterrupted()) {
        LOG.debug("Skipping adding watch since current thread is interrupted.");
    }

    // check if directory is already watched
    // on Windows, check if any parent is already watched
    for (Path path = dir; path != null; path = FILE_TREE_WATCHING_SUPPORTED ? path.getParent() : null) {
        WatchKey previousWatchKey = watchKeys.get(path);
        if (previousWatchKey != null && previousWatchKey.isValid()) {
            LOG.debug("Directory {} is already watched and the watch is valid, not adding another one.", path);
            return;
        }
    }

    int retryCount = 0;
    IOException lastException = null;
    while (retryCount++ < 2) {
        try {
            WatchKey watchKey = dir.register(watchService, WATCH_KINDS, WATCH_MODIFIERS);
            watchKeys.put(dir, watchKey);
            return;
        } catch (IOException e) {
            LOG.debug("Exception in registering for watching of " + dir, e);
            lastException = e;

            if (e instanceof NoSuchFileException) {
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            }

            if (e instanceof FileSystemException && e.getMessage() != null && e.getMessage().contains("Bad file descriptor")) {
                // retry after getting "Bad file descriptor" exception
                LOG.debug("Retrying after 'Bad file descriptor'");
                continue;
            }

            // Windows at least will sometimes throw odd exceptions like java.nio.file.AccessDeniedException
            // if the file gets deleted while the watch is being set up.
            // So, we just ignore the exception if the dir doesn't exist anymore
            if (!Files.exists(dir)) {
                // return silently when directory doesn't exist
                LOG.debug("Return silently since directory doesn't exist.");
                return;
            } else {
                // no retry
                throw e;
            }
        }
    }
    LOG.debug("Retry count exceeded, throwing last exception");
    throw lastException;
}
 
开发者ID:lxxlxx888,项目名称:Reer,代码行数:55,代码来源:WatchServiceRegistrar.java

示例3: nextEvent

import java.nio.file.WatchKey; //导入依赖的package包/类
@Override
protected String nextEvent() throws IOException, InterruptedException {
    WatchKey key;
    try {
        key = watcher.take();
    } catch (ClosedWatchServiceException cwse) { // #238261
        @SuppressWarnings({"ThrowableInstanceNotThrown"})
        InterruptedException ie = new InterruptedException();
        throw (InterruptedException) ie.initCause(cwse);
    }
    Path dir = (Path)key.watchable();
           
    String res = dir.toAbsolutePath().toString();
    for (WatchEvent<?> event: key.pollEvents()) {
        if (event.kind() == OVERFLOW) {
            // full rescan
            res = null;
        }
    }
    key.reset();
    return res;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:23,代码来源:NioNotifier.java

示例4: run

import java.nio.file.WatchKey; //导入依赖的package包/类
@Override
public void run() {
    WatchService watchService = WatchServiceUtil.watchModify(pluginDir);
    WatchKey key;
    while (watchService != null){
        try {
            key = watchService.take();
            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                if(watchEvent.kind() == ENTRY_MODIFY){
                    String fileName = watchEvent.context() == null ? "" : watchEvent.context().toString();
                    Plugin plugin = PluginLibraryHelper.getPluginByConfigFileName(fileName);
                    if(plugin != null){
                        plugin.init(PluginLibraryHelper.getPluginConfig(plugin));
                        log.info("已完成插件{}的配置重新加载",plugin.pluginName());
                    }
                }
            }
            key.reset();
        } catch (Exception e) {
            log.error("插件配置文件监听异常",e);
            break;
        }
    }
}
 
开发者ID:DevopsJK,项目名称:SuitAgent,代码行数:25,代码来源:PluginPropertiesWatcher.java

示例5: processSubevents

import java.nio.file.WatchKey; //导入依赖的package包/类
/**
 * Processes subevents of the key.
 * @param key That has new events.
 * @param dir For the key.
 * @throws IOException If a subdirectory cannot be registered.
 */
private void processSubevents(final WatchKey key, final Path dir)
    throws IOException {
    for (final WatchEvent event : key.pollEvents()) {
        final WatchEvent.Kind kind = event.kind();
        final Path name = (Path) event.context();
        final Path child = dir.resolve(name);
        Logger.debug(
            this,
            "%s: %s%n", event.kind().name(), child
        );
        if (kind == ENTRY_CREATE) {
            try {
                if (Files.isDirectory(child)) {
                    this.processSubevents(child);
                }
            } catch (final IOException ex) {
                throw new IOException(
                    "Failed to register subdirectories.",
                    ex
                );
            }
        }
    }
}
 
开发者ID:driver733,项目名称:VKMusicUploader,代码行数:31,代码来源:WatchDirs.java

示例6: setWatcherOnThemeFile

import java.nio.file.WatchKey; //导入依赖的package包/类
private static void setWatcherOnThemeFile() {
    try {
        WatchService watchService = FileSystems.getDefault().newWatchService();
        WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        while (true) {
            final WatchKey wk = watchService.take();
            for (WatchEvent<?> event : wk.pollEvents()) {
                //we only register "ENTRY_MODIFY" so the context is always a Path.
                final Path changed = (Path) event.context();
                System.out.println(changed);
                if (changed.endsWith("Theme.css")) {
                    System.out.println("Theme.css has changed...reloading stylesheet.");
                    scene.getStylesheets().clear();
                    scene.getStylesheets().add("resources/Theme.css");
                }
            }
            boolean valid = wk.reset();
            if (!valid)
                System.out.println("Watch Key has been reset...");
        }
    } catch (Exception e) { /*Thrown to void*/ }
}
 
开发者ID:maximstewart,项目名称:UDE,代码行数:23,代码来源:UFM.java

示例7: registerRecursively

import java.nio.file.WatchKey; //导入依赖的package包/类
private void registerRecursively(final Path directory) throws IOException {
    Files.walkFileTree(directory, new SimpleFileVisitor<Path>() {
        @Override
        public FileVisitResult preVisitDirectory(final Path visitedDirectory, final BasicFileAttributes attrs) throws IOException {
            if (!FileSystemWatcher.this.watchedFiles.matchesDirectory(visitedDirectory)) {
                return FileVisitResult.SKIP_SUBTREE;
            }


            final WatchKey key = visitedDirectory.register(watcher,
                    ENTRY_CREATE,
                    ENTRY_MODIFY,
                    ENTRY_DELETE);

            watchedPaths.put(key, visitedDirectory);

            return FileVisitResult.CONTINUE;
        }
    });
}
 
开发者ID:openweb-nl,项目名称:hippo-groovy-updater,代码行数:21,代码来源:FileSystemWatcher.java

示例8: pollForMoreChanges

import java.nio.file.WatchKey; //导入依赖的package包/类
/**
 * Keep polling for a short time: when (multiple) directories get deleted the watch keys might
 * arrive just a bit later
 */
private void pollForMoreChanges() throws ClosedWatchServiceException, InterruptedException {
    boolean keepPolling = true;
    List<WatchKey> polledKeys = new ArrayList<>();
    final long startPolling = System.currentTimeMillis();
    while (keepPolling) {
        log.debug("Waiting {} ms for more changes...", POLLING_TIME_MILLIS);
        WatchKey key = watcher.poll(POLLING_TIME_MILLIS, TimeUnit.MILLISECONDS);
        if (key == null) {
            keepPolling = false;
        } else {
            log.debug("Found change for '{}' found during extra polling time", key.watchable());
            polledKeys.add(key);
        }
    }
    log.debug("Polled '{}' more changes during '{}' ms", polledKeys.size(), String.valueOf(System.currentTimeMillis() - startPolling));
    for (WatchKey polledKey : polledKeys) {
        processWatchKey(polledKey);
    }
}
 
开发者ID:openweb-nl,项目名称:hippo-groovy-updater,代码行数:24,代码来源:FileSystemWatcher.java

示例9: run

import java.nio.file.WatchKey; //导入依赖的package包/类
@SuppressWarnings("unchecked")
@Override
public void run() {
	while (running) {
		try {
			final WatchKey watchKey = watcher.take();
			for (final WatchEvent<?> event : watchKey.pollEvents()) {
				Path changed = (Path) event.context();
				if (changed == null || event.kind() == StandardWatchEventKinds.OVERFLOW) {
					System.out.println("bad file watch event: " + event);
					continue;
				}
				changed = watchedDirectory.resolve(changed);
				for (final ListenerAndPath x : listeners) {
					if (Thread.interrupted() && !running)
						return;
					if (changed.startsWith(x.startPath)) {
						x.listener.fileChanged(changed, (Kind<Path>) event.kind());
					}
				}
			}
			watchKey.reset();
		} catch (final InterruptedException e) {}
	}
}
 
开发者ID:Njol,项目名称:Motunautr,代码行数:26,代码来源:FileWatcher.java

示例10: run

import java.nio.file.WatchKey; //导入依赖的package包/类
@Override
protected void run() {
    while(isRunning()) {
        try {
            final WatchKey key = watchService.take();
            final WatchedDirectory watchedDirectory = dirsByKey.get(key);
            if(watchedDirectory == null) {
                logger.warning("Cancelling unknown key " + key);
                key.cancel();
            } else {
                for(WatchEvent<?> event : key.pollEvents()) {
                    watchedDirectory.dispatch((WatchEvent<Path>) event);
                }
                key.reset();
            }
        } catch(InterruptedException e) {
            // ignore, just check for termination
        }
    }
}
 
开发者ID:OvercastNetwork,项目名称:ProjectAres,代码行数:21,代码来源:PathWatcherServiceImpl.java

示例11: manageDirectoryDeletion

import java.nio.file.WatchKey; //导入依赖的package包/类
private void manageDirectoryDeletion(Path filename) throws IOException {
    PhotatoFolder parentFolder = getCurrentFolder(filename.getParent());
    parentFolder.subFolders.remove(filename.getFileName().toString());
    WatchKey removed = watchedDirectoriesKeys.remove(filename);
    if (removed != null) {
        removed.cancel();
        watchedDirectoriesPaths.remove(removed);
    }

    PhotatoFolder currentFolder = getCurrentFolder(filename);
    if (currentFolder.medias != null) {
        for (PhotatoMedia media : currentFolder.medias) {
            try {
                searchManager.removeMedia(media);
                albumsManager.removeMedia(media);
                thumbnailGenerator.deleteThumbnail(media.fsPath, media.lastModificationTimestamp);
                fullScreenImageGetter.deleteImage(media);
            } catch (IOException ex) {
            }
        }
    }
}
 
开发者ID:trebonius0,项目名称:Photato,代码行数:23,代码来源:PhotatoFilesManager.java

示例12: simpleTest

import java.nio.file.WatchKey; //导入依赖的package包/类
public void simpleTest(Path path) throws Exception
{
	WatchService watchService=FileSystems.getDefault().newWatchService();  
	path.register(watchService,   
            StandardWatchEventKinds.ENTRY_CREATE,  
            StandardWatchEventKinds.ENTRY_DELETE,  
            StandardWatchEventKinds.ENTRY_MODIFY);  
    while(true)  
    {  
        WatchKey watchKey=watchService.take();  
           List<WatchEvent<?>> watchEvents = watchKey.pollEvents();  
           for(WatchEvent<?> event : watchEvents){  
               //TODO 根据事件类型采取不同的操作。。。。。。。  
               System.out.println("["+event.context()+"]文件发生了["+event.kind()+"]事件");    
           }  
           watchKey.reset(); 
    } 
}
 
开发者ID:juebanlin,项目名称:util4j,代码行数:19,代码来源:FileMonitorJdkImpl.java

示例13: FileWatcher

import java.nio.file.WatchKey; //导入依赖的package包/类
private FileWatcher(Map<Path, Consumer<Path>> registeredPaths) {
  this.registeredPaths = ImmutableMap.copyOf(registeredPaths);
  try {
    watchService = FileSystems.getDefault().newWatchService();
    ImmutableMap.Builder<WatchKey, Path> watchedDirsBuilder = ImmutableMap.builder();
    for (Map.Entry<Path, Consumer<Path>> entry : registeredPaths.entrySet()) {
      Path dir = entry.getKey().getParent();
      WatchKey key =
          dir.register(
              watchService,
              StandardWatchEventKinds.ENTRY_CREATE,
              StandardWatchEventKinds.ENTRY_DELETE,
              StandardWatchEventKinds.ENTRY_MODIFY);
      watchedDirsBuilder.put(key, dir);
    }
    this.watchedDirs = watchedDirsBuilder.build();
  } catch (IOException e) {
    throw new UncheckedIOException("Could not create WatchService.", e);
  }
  executor = Executors.newSingleThreadScheduledExecutor();
}
 
开发者ID:curioswitch,项目名称:curiostack,代码行数:22,代码来源:FileWatcher.java

示例14: handle

import java.nio.file.WatchKey; //导入依赖的package包/类
/**
 * Stress the given WatchService, specifically the cancel method, in
 * the given directory. Closes the WatchService when done.
 */
static void handle(Path dir, WatchService watcher) {
    try {
        try {
            Path file = dir.resolve("anyfile");
            for (int i=0; i<2000; i++) {
                WatchKey key = dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE);
                Files.createFile(file);
                Files.delete(file);
                key.cancel();
            }
        } finally {
            watcher.close();
        }
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:23,代码来源:LotsOfCancels.java

示例15: poll

import java.nio.file.WatchKey; //导入依赖的package包/类
/**
 * Polls the given WatchService in a tight loop. This keeps the event
 * queue drained, it also hogs a CPU core which seems necessary to
 * tickle the original bug.
 */
static void poll(WatchService watcher) {
    try {
        for (;;) {
            WatchKey key = watcher.take();
            if (key != null) {
                key.pollEvents();
                key.reset();
            }
        }
    } catch (ClosedWatchServiceException expected) {
        // nothing to do
    } catch (Exception e) {
        e.printStackTrace();
        failed = true;
    }
}
 
开发者ID:lambdalab-mirror,项目名称:jdk8u-jdk,代码行数:22,代码来源:LotsOfCancels.java


注:本文中的java.nio.file.WatchKey类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。