Example usage for java.nio.file StandardWatchEventKinds ENTRY_CREATE

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

Introduction

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

Prototype

WatchEvent.Kind ENTRY_CREATE

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

Click Source Link

Document

Directory entry created.

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;
                }/*from w ww .j a va 2 s.co  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: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 w  w  . j  a  v  a2 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  .  j  av  a 2s.  co  m*/
        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: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;
                }//  w w  w. ja  v a  2s .  co 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:SecurityWatch.java

public void watchVideoCamera(Path path) throws IOException, InterruptedException {

    watchService = FileSystems.getDefault().newWatchService();
    register(path, StandardWatchEventKinds.ENTRY_CREATE);

    OUTERMOST: while (true) {

        final WatchKey key = watchService.poll(11, TimeUnit.SECONDS);

        if (key == null) {
            System.out.println("The video camera is jammed - security watch system is canceled!");
            break;
        } else {/*from  w w  w  . j  a  va  2  s . c  o  m*/

            for (WatchEvent<?> watchEvent : key.pollEvents()) {

                final Kind<?> kind = watchEvent.kind();

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

                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {

                    //get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();
                    final Path child = path.resolve(filename);

                    if (Files.probeContentType(child).equals("image/jpeg")) {

                        //print it out the video capture time
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
                        System.out.println("Video capture successfully at: " + dateFormat.format(new Date()));
                    } else {
                        System.out.println("The video camera capture format failed! This could be a virus!");
                        break OUTERMOST;
                    }
                }
            }

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

    watchService.close();
}

From source file:SecurityWatch.java

public void watchVideoCamera(Path path) throws IOException, InterruptedException {

    watchService = FileSystems.getDefault().newWatchService();
    register(path, StandardWatchEventKinds.ENTRY_CREATE);

    OUTERMOST: while (true) {

        final WatchKey key = watchService.poll();

        if (key == null) {
            System.out.println("The video camera is jammed - security watch system is canceled!");
            break;
        } else {/*from  w w w. j a  v  a  2  s  .  c om*/

            for (WatchEvent<?> watchEvent : key.pollEvents()) {

                final Kind<?> kind = watchEvent.kind();

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

                if (kind == StandardWatchEventKinds.ENTRY_CREATE) {

                    //get the filename for the event
                    final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
                    final Path filename = watchEventPath.context();
                    final Path child = path.resolve(filename);

                    if (Files.probeContentType(child).equals("image/jpeg")) {

                        //print it out the video capture time
                        SimpleDateFormat dateFormat = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
                        System.out.println("Video capture successfully at: " + dateFormat.format(new Date()));
                    } else {
                        System.out.println("The video camera capture format failed! This could be a virus!");
                        break OUTERMOST;
                    }
                }
            }

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

    watchService.close();
}

From source file:eu.edisonproject.rest.FolderWatcherRunnable.java

@Override
public void run() {
    final Path path = FileSystems.getDefault().getPath(dir);
    try (final WatchService watchService = FileSystems.getDefault().newWatchService()) {
        final WatchKey watchKey = path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
        while (true) {
            final WatchKey wk = watchService.take();
            for (WatchEvent<?> event : wk.pollEvents()) {

                final Path changed = (Path) event.context();
                executeClassification(new File(dir + File.separator + changed));
            }//  ww  w . j  ava2  s  .  c o m
            // reset the key
            boolean valid = wk.reset();
            if (!valid) {
                Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.WARNING,
                        "Key has been unregisterede");
            }
        }
    } catch (IOException ex) {
        Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex);
    } catch (InterruptedException ex) {
        Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex);
    } catch (Exception ex) {
        Logger.getLogger(FolderWatcherRunnable.class.getName()).log(Level.SEVERE, null, ex);
    }
}

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  ww.  ja va2s.co  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:org.apache.logging.log4j.core.appender.rolling.RollingAppenderDirectWriteTempCompressedFilePatternTest.java

@Test
public void testAppender() throws Exception {
    final File dir = new File(DIR);
    dir.mkdirs();/*w w w  .java2 s . co  m*/
    try (final WatchService watcher = FileSystems.getDefault().newWatchService()) {
        WatchKey key = dir.toPath().register(watcher, StandardWatchEventKinds.ENTRY_CREATE);

        for (int i = 0; i < 100; ++i) {
            logger.debug("This is test message number " + i);
        }
        Thread.sleep(50);
        assertTrue("Directory not created", dir.exists() && dir.listFiles().length > 0);
        final File[] files = dir.listFiles();
        assertNotNull(files);
        assertThat(files, hasItemInArray(that(hasName(that(endsWith(".gz"))))));

        int temporaryFilesCreated = 0;
        int compressedFiles = 0;
        key = watcher.take();

        for (final WatchEvent<?> event : key.pollEvents()) {
            final WatchEvent<Path> ev = (WatchEvent<Path>) event;
            final Path filename = ev.context();
            if (filename.toString().endsWith(".tmp")) {
                temporaryFilesCreated++;
            }
            if (filename.toString().endsWith(".gz")) {
                compressedFiles++;
            }
        }
        assertTrue("No temporary file created during compression", temporaryFilesCreated > 0);
        assertTrue("Temporarys file created not equals to compressed files",
                compressedFiles == temporaryFilesCreated);
    }
}