Example usage for java.nio.file WatchKey pollEvents

List of usage examples for java.nio.file WatchKey pollEvents

Introduction

In this page you can find the example usage for java.nio.file WatchKey pollEvents.

Prototype

List<WatchEvent<?>> pollEvents();

Source Link

Document

Retrieves and removes all pending events for this watch key, returning a List of the events that were retrieved.

Usage

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;
                }//  w  w  w.  j  a v  a2 s.  c o m
                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:Test.java

public static void main(String[] args) throws Exception {
    WatchService watcher = FileSystems.getDefault().newWatchService();

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

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

    while (true) {
        key = watcher.take();/*  w  w w.j  a v a2 s  .c  o m*/
        for (WatchEvent<?> event : key.pollEvents()) {
            if (event.kind() == ENTRY_MODIFY) {
                System.out.println("Home dir changed!");
            }
        }
        key.reset();
    }
}

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  ww  w  .j a  v  a  2 s .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();/*from   w  ww .ja  v a 2  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) 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();/*  w ww  .  j av a2 s . com*/

        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:org.apache.tomee.jul.handler.rotating.ArchivingTest.java

private static void watch(final WatchKey key) {

    if (watcherThread != null) {
        // tell the old watchter thread to shutdown
        watcherThread.interrupt();//from ww w  .j a  v a  2s. c om
    }

    watcherThread = new Thread("ArchivingTest.watch") {
        @Override
        public void run() {

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

                    if (kind == StandardWatchEventKinds.OVERFLOW) {
                        continue;
                    }

                    if (watcherThread != this || isInterrupted()) {
                        return;
                    }

                    lastEvent.set(event);

                    latch.get().countDown();
                }

                final boolean valid = key.reset();
                if (!valid) {
                    System.out.println("ArchivingTest.watch terminated");
                    break;
                }
            }
        }
    };

    watcherThread.start();
}

From source file:request.processing.ServletLoader.java

/**
 * Watch dir monitors the current directory for any new files and calls
 * loadJar on them.//from w  w w . ja va2s. co  m
 */
public static void watchDir() {

    WatchService watcher = null;
    try {
        watcher = FileSystems.getDefault().newWatchService();
        WatchKey key = servletDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
        servletDir.register(watcher, StandardWatchEventKinds.ENTRY_MODIFY);
    } catch (IOException x) {
        System.err.println(x);
    }

    while (true) {
        WatchKey key = null;
        try {
            key = watcher.take();

        } catch (InterruptedException x) {
            System.err.println("Interrupted Exception");
            x.printStackTrace();
        }

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

            if (kind == StandardWatchEventKinds.OVERFLOW) {
                continue;
            }

            try {
                System.out.println("Directory Changed!");
                Thread.sleep(1000);
                loadServletsAndConfig();
            } catch (Exception e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

            boolean valid = key.reset();
            if (!valid) {
                break;
            }
        }
    }

}

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  w  w w . j  ava  2  s  .com
                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.playonlinux.filesystem.DirectoryWatcher.java

public void run() {
    try {//w  ww.  j a v  a  2 s. co  m
        WatchKey key = watcher.take();
        key.pollEvents();
        notifyConsumer();

        while (key.reset()) {
            key = watcher.take();
            key.pollEvents();
            notifyConsumer();
        }
    } catch (InterruptedException e) {
        throw new RuntimeException(String.format("Watcher Interupted for %s", observedDirectory.toString()));
    }
}

From source file:org.balloon_project.overflight.task.importer.ImporterFileListener.java

@Override
public void run() {
    // TODO initial import start
    // initial import of existing file
    logger.info("Scanning for files to import");
    File importDir = new File(configuration.getDatabaseImportDirectory());
    if (importDir.exists() && importDir.isDirectory()) {
        for (File file : importDir.listFiles()) {
            if (file.isFile() && file.getPath().endsWith(IndexingTask.N_TRIPLES_EXTENSION)) {
                logger.info("File event: Adding " + file.toString() + " to importer queue");
                importer.startImporting(file);
            }/*from   w  w  w . ja v a 2s  . co  m*/
        }
    }

    // starting file watch service for future files
    try {
        String path = configuration.getDatabaseImportDirectory();
        logger.info("Starting import file listener for path " + path);
        Path tmpPath = Paths.get(path);
        WatchService watchService = FileSystems.getDefault().newWatchService();
        tmpPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);

        for (;;) {
            WatchKey key = watchService.take();

            for (WatchEvent event : key.pollEvents()) {
                if (event.kind().name() == "OVERFLOW") {
                    continue;
                } else {
                    WatchEvent<Path> ev = (WatchEvent<Path>) event;
                    Path filename = ev.context();
                    logger.info("File event: Adding " + filename.toString() + " to importer queue");
                    importer.startImporting(tmpPath.resolve(filename).toFile());
                }
            }

            // Reset the key -- this step is critical if you want to
            // receive further watch events.  If the key is no longer valid,
            // the directory is inaccessible so exit the loop.
            boolean valid = key.reset();
            if (!valid) {
                break;
            }

        }
    } catch (IOException | InterruptedException e) {
        e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
    } finally {
        logger.debug("Stopping import file listener");
    }
}