Example usage for java.nio.file StandardWatchEventKinds ENTRY_DELETE

List of usage examples for java.nio.file StandardWatchEventKinds ENTRY_DELETE

Introduction

In this page you can find the example usage for java.nio.file StandardWatchEventKinds ENTRY_DELETE.

Prototype

WatchEvent.Kind ENTRY_DELETE

To view the source code for java.nio.file StandardWatchEventKinds ENTRY_DELETE.

Click Source Link

Document

Directory entry deleted.

Usage

From source file:Main.java

public static void main(String[] args) throws Exception {

    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("c:/");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();

        System.out.println("Path being watched: " + watchKey.watchable());
        System.out.println();/*from w w  w .  j  a va  2  s. co  m*/

        if (watchKey.isValid()) {
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                System.out.println("Kind: " + event.kind());
                System.out.println("Context: " + event.context());
                System.out.println("Count: " + event.count());
                System.out.println();
            }

            boolean valid = watchKey.reset();
            if (!valid) {
                // The watchKey is not longer registered
            }
        }
    }

}

From source file:Test.java

public static void main(String[] args) throws Exception {
    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("/home/docs");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();
        System.out.println("Path being watched: " + watchKey.watchable());
        if (watchKey.isValid() == false) {
            return;
        }//from w w  w  .ja v a  2s . c  om
        for (WatchEvent<?> event : watchKey.pollEvents()) {
            System.out.println("Kind: " + event.kind());
            System.out.println("Context: " + event.context());
            System.out.println("Count: " + event.count());
            System.out.println();
        }
        boolean valid = watchKey.reset();
        System.out.println(valid);

    }
}

From source file:Main.java

public static void main(String[] args) throws Exception {
    FileSystem fileSystem = FileSystems.getDefault();
    WatchService watchService = fileSystem.newWatchService();
    Path directory = Paths.get("c:/");
    WatchEvent.Kind<?>[] events = { StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
            StandardWatchEventKinds.ENTRY_MODIFY };
    directory.register(watchService, events);
    while (true) {
        System.out.println("Waiting for a watch event");
        WatchKey watchKey = watchService.take();

        System.out.println("Path being watched: " + watchKey.watchable());
        System.out.println();/* www. ja  v a2 s . c  o m*/

        if (watchKey.isValid()) {
            for (WatchEvent<?> event : watchKey.pollEvents()) {
                System.out.println("Kind: " + event.kind());
                System.out.println("Context: " + event.context());
                System.out.println("Count: " + event.count());
                System.out.println();
            }

            boolean valid = watchKey.reset();
            if (!valid) {
                // The watchKey is not longer registered
            }
        }
    }

}

From source file:Main.java

public static void main(String[] args) {
    try (WatchService ws = FileSystems.getDefault().newWatchService()) {
        Path dirToWatch = Paths.get("C:\\myName");
        dirToWatch.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE);
        while (true) {
            WatchKey key = ws.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                Kind<?> eventKind = event.kind();
                if (eventKind == StandardWatchEventKinds.OVERFLOW) {
                    System.out.println("Event  overflow occurred");
                    continue;
                }/*from w w  w.  ja  v a  2  s. com*/
                WatchEvent<Path> currEvent = (WatchEvent<Path>) event;
                Path dirEntry = currEvent.context();
                System.out.println(eventKind + "  occurred on  " + dirEntry);
            }
            boolean isKeyValid = key.reset();
            if (!isKeyValid) {
                System.out.println("No  longer  watching " + dirToWatch);
                break;
            }
        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace();
    }
}

From source file:MyWatch.java

public void watchRNDir(Path path) throws IOException, InterruptedException {
    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
        path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_DELETE);

        while (true) {
            // retrieve and remove the next watch key
            final WatchKey key = watchService.take();

            for (WatchEvent<?> watchEvent : key.pollEvents()) {
                final Kind<?> kind = watchEvent.kind();
                if (kind == StandardWatchEventKinds.OVERFLOW) {
                    continue;
                }/*from  ww  w . java  2  s .c o  m*/
                final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                final Path filename = watchEventPath.context();
                System.out.println(kind + " -> " + filename);
            }

            boolean valid = key.reset();

            if (!valid) {
                break;
            }
        }
    }
}

From source file:com.ilscipio.scipio.common.FileListener.java

/**
 *  Start a file listener (WatchService) and run a service of a given name and writes the result to the database
 *  Can be used to implements EECAs to auto-update information based on file changes
 **///from  w  w  w.ja va 2 s  . c  o m
public static void startFileListener(String name, String location) {

    try {
        if (UtilValidate.isNotEmpty(name) && UtilValidate.isNotEmpty(location)) {

            if (getThreadByName(name) != null) {
                Debug.logInfo("Filelistener " + name + " already started. Skipping...", module);
            } else {
                URL resLocation = UtilURL.fromResource(location);
                Path folderLocation = Paths.get(resLocation.toURI());
                if (folderLocation == null) {
                    throw new UnsupportedOperationException("Directory not found");
                }

                final WatchService folderWatcher = folderLocation.getFileSystem().newWatchService();
                // register all subfolders
                Files.walkFileTree(folderLocation, new SimpleFileVisitor<Path>() {
                    @Override
                    public FileVisitResult preVisitDirectory(Path dir, BasicFileAttributes attrs)
                            throws IOException {
                        dir.register(folderWatcher, StandardWatchEventKinds.ENTRY_CREATE,
                                StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
                        return FileVisitResult.CONTINUE;
                    }
                });

                // start the file watcher thread below
                ScipioWatchQueueReader fileListener = new ScipioWatchQueueReader(folderWatcher, name, location);
                ScheduledExecutorService executor = ExecutionPool.getScheduledExecutor(
                        FILE_LISTENER_THREAD_GROUP, "filelistener-startup",
                        Runtime.getRuntime().availableProcessors(), 0, true);
                try {
                    executor.submit(fileListener, name);
                } finally {
                    executor.shutdown();
                }
                Debug.logInfo("Starting FileListener thread for " + name, module);
            }
        }
    } catch (Exception e) {
        Debug.logError("Could not start FileListener " + name + " for " + location + "\n" + e, module);

    }
}

From source file:io.stallion.fileSystem.FileSystemWatcherRunner.java

private void registerWatcherForFolder(IWatchEventHandler handler, String folder) {
    Path itemsDir = FileSystems.getDefault().getPath(folder);
    try {/*from w w w . j ava 2s .c o m*/
        if (new File(itemsDir.toString()).isDirectory()) {
            itemsDir.register(watcher,
                    new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_MODIFY,
                            StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE },
                    SensitivityWatchEventModifier.HIGH);
            Log.fine("Folder registered with watcher {0}", folder);
        }
    } catch (IOException e) {
        throw new RuntimeException(e);
    }
}

From source file:de.elomagic.carafile.client.CaraCloud.java

/**
 * Starts synchronization of the given base path with the registry.
 * <p/>//  w w w  . j a  va 2 s  .c o  m
 * This method will block till call method {@link CaraCloud#stop() }
 *
 * @throws IOException Thrown when an I/O error occurs
 * @throws InterruptedException Thrown when method stop was called or application will terminate
 * @throws GeneralSecurityException
 */
public void start() throws IOException, InterruptedException, GeneralSecurityException {
    if (client == null) {
        throw new IllegalStateException("Attribute \"client\" must be set.");
    }

    if (basePath == null) {
        throw new IllegalStateException("Attribute \"basePath\" must be set.");
    }

    if (!Files.exists(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must exists.");
    }

    if (!Files.isDirectory(basePath)) {
        throw new IllegalStateException("Path \"" + basePath + "\" must be a directory/folder.");
    }

    watcher = FileSystems.getDefault().newWatchService();
    registerDefaultWatch(basePath);

    while (!Thread.interrupted()) {
        WatchKey key = watcher.take();
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                Path path = basePath.resolve(event.context().toString());
                createFile(path);
            } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {

            } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                Path path = basePath.resolve(event.context().toString());
                deleteFile(path);
            } else {
                LOG.error("Unsupported kind: " + event.kind() + ", path: " + event.context());
            }
        }

        key.reset();
    }
}

From source file:io.mangoo.build.Watcher.java

/**
 *
 * USUALLY THIS IS THE DEFAULT WAY TO REGISTER THE EVENTS:
 *
 * WatchKey watchKey = path.register(//from w w w. j ava  2  s.c  o  m
 *    watchService,
 *    ENTRY_CREATE,
 *    ENTRY_DELETE,
 *    ENTRY_MODIFY);
 *
 *  BUT THIS IS DAMN SLOW (at least on a Mac)
 *  THEREFORE WE USE EVENTS FROM COM.SUN PACKAGES THAT ARE WAY FASTER
 *  THIS MIGHT BREAK COMPATIBILITY WITH OTHER JDKs
 *   MORE: http://stackoverflow.com/questions/9588737/is-java-7-watchservice-slow-for-anyone-else
 *
 * @param path
 * @throws IOException
 */
private void register(Path path) throws IOException {
    WatchKey watchKey = path.register(watchService,
            new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_CREATE, //NOSONAR
                    StandardWatchEventKinds.ENTRY_MODIFY, //NOSONAR
                    StandardWatchEventKinds.ENTRY_DELETE //NOSONAR
            }, SensitivityWatchEventModifier.HIGH);

    watchKeys.put(watchKey, path);
}

From source file:com.temenos.interaction.loader.detector.DirectoryChangeActionNotifier.java

protected void initWatchers(Collection<? extends File> resources) {
    if (scheduledTask != null) {
        scheduledTask.cancel(true);//  www . j a va2s .  c  o  m
    }
    if (resources == null || resources.isEmpty() || getListeners() == null || getListeners().isEmpty()) {
        return;
    }
    try {
        WatchService ws = FileSystems.getDefault().newWatchService();
        for (File file : resources) {
            Path filePath = Paths.get(file.toURI());
            filePath.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY,
                    StandardWatchEventKinds.ENTRY_DELETE);
        }

        watchService = ws;
        scheduledTask = executorService.scheduleWithFixedDelay(
                new ListenerNotificationTask(watchService, getListeners(), getIntervalSeconds() * 1000), 5,
                getIntervalSeconds(), TimeUnit.SECONDS);
    } catch (IOException ex) {
        throw new RuntimeException("Error configuring directory change listener - unexpected IOException", ex);
    }
}