本文整理匯總了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();
}
}
示例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;
}
示例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;
}
示例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;
}
}
}
示例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
);
}
}
}
}
示例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*/ }
}
示例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;
}
});
}
示例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);
}
}
示例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) {}
}
}
示例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
}
}
}
示例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) {
}
}
}
}
示例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();
}
}
示例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();
}
示例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;
}
}
示例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;
}
}