Example usage for java.nio.file StandardWatchEventKinds ENTRY_MODIFY

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

Introduction

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

Prototype

WatchEvent.Kind ENTRY_MODIFY

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

Click Source Link

Document

Directory entry modified.

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 .ja v a2  s .c om
                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.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: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  va 2  s .  c  o 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 ww w  .j  a  v  a2s . c  om

        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;
                }/*from www .  j av a2s .  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.xiaomi.linden.common.util.FileChangeWatcher.java

@Override
public void run() {
    try {//  ww w  .  j  av  a 2  s  .  c  o  m
        watcher = FileSystems.getDefault().newWatchService();
        Path path = new File(absolutePath).toPath().getParent();
        String fileWatched = FilenameUtils.getName(absolutePath);
        path.register(watcher, new WatchEvent.Kind[] { StandardWatchEventKinds.ENTRY_MODIFY },
                SensitivityWatchEventModifier.HIGH);
        LOGGER.info("File watcher start to watch {}", absolutePath);

        while (isAlive()) {
            try {
                Thread.sleep(interval);
                WatchKey key = watcher.poll(1000l, TimeUnit.MILLISECONDS);
                if (key == null) {
                    continue;
                }

                List<WatchEvent<?>> events = key.pollEvents();
                for (WatchEvent<?> event : events) {
                    if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                        String file = event.context().toString();
                        if (fileWatched.equals(file)) {
                            doOnChange();
                        }
                    }
                }

                if (!key.reset()) {
                    LOGGER.info("File watcher key not valid.");
                }
            } catch (InterruptedException e) {
                LOGGER.error("File watcher thread exit!");
                break;
            }
        }
    } catch (Throwable e) {
        LOGGER.error("File watcher error {}", Throwables.getStackTraceAsString(e));
    }
}

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 . j a va 2 s . com*/
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.wso2.carbon.uuf.renderablecreator.html.internal.io.HtmlRenderableUpdater.java

public void add(MutableHtmlRenderable mutableHtmlRenderable) {
    Path renderablePath = Paths.get(mutableHtmlRenderable.getAbsoluteFilePath());
    Path parentDirectory = renderablePath.getParent();
    if (watchingDirectories.add(parentDirectory)) {
        try {//from   w w  w.j a  v  a2s  .co m
            parentDirectory.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        } catch (ClosedWatchServiceException e) {
            throw new UUFException("File watch service is closed.", e);
        } catch (NotDirectoryException e) {
            throw new FileOperationException("Cannot register path '" + parentDirectory
                    + "' to file watch service as it is not a directory.", e);
        } catch (IOException e) {
            throw new FileOperationException("An IO error occurred when registering path '" + parentDirectory
                    + "' to file watch service.'", e);
        }
    }
    watchingRenderables.put(renderablePath, mutableHtmlRenderable);
}

From source file:org.codelibs.empros.agent.watcher.file.FileWatcher.java

@Override
@SuppressWarnings("restriction")
public void start() {
    if (started.getAndSet(true)) {
        return;//  w  w  w  .  ja  va2  s .co  m
    }

    int count = 0;
    while (true) {
        count++;

        final String key = "watchPath" + count;
        final String value = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES, key, null);
        if (StringUtils.isEmpty(value)) {
            break;
        }

        final File file = new File(value);
        if (!file.isDirectory()) {
            continue;
        }

        final String kindStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".kinds", key,
                "create,modify,delete,overflow");
        final String[] kinds = kindStr.split(",");
        final List<Kind<?>> kindList = new ArrayList<Kind<?>>(4);
        for (final String kind : kinds) {
            if (StringUtils.isNotBlank(kind)) {
                switch (kind.trim()) {
                case "create":
                    kindList.add(StandardWatchEventKinds.ENTRY_CREATE);
                    break;
                case "modify":
                    kindList.add(StandardWatchEventKinds.ENTRY_MODIFY);
                    break;
                case "delete":
                    kindList.add(StandardWatchEventKinds.ENTRY_DELETE);
                    break;
                case "overflow":
                    kindList.add(StandardWatchEventKinds.OVERFLOW);
                    break;
                default:
                    logger.warn("unknown kind: {}", kind);
                    break;
                }
            }
        }

        final String modifierStr = PropertiesUtil.getAsString(FILEWATCHER_PROPERTIES + ".modifiers", key, "");
        final String[] modifiers = modifierStr.split(",");
        final List<WatchEvent.Modifier> modifierList = new ArrayList<WatchEvent.Modifier>(4);
        for (final String modifier : modifiers) {
            if (StringUtils.isNotBlank(modifier)) {
                switch (modifier.trim()) {
                case "fileTree":
                    modifierList.add(com.sun.nio.file.ExtendedWatchEventModifier.FILE_TREE);
                    break;
                default:
                    logger.warn("unknown modifier: {}", modifier);
                    break;
                }
            }
        }

        fileWatcherList
                .add(new FileWatchTask(eventManager, file.toPath(), kindList.toArray(new Kind[kindList.size()]),
                        modifierList.toArray(new WatchEvent.Modifier[modifierList.size()])));

    }

    if (fileWatcherList.isEmpty()) {
        logger.info("Cannot find path setting.");
        // TODO shutdown fook
        return;
    }

    for (final FileWatchTask fileWatchTask : fileWatcherList) {
        fileWatchTask.start();
    }

}

From source file:org.brekka.stillingar.spring.snapshot.WatchedResourceMonitor.java

@Override
public void initialise(Resource resource) {
    try {/*from   w  w  w  .  java  2 s .  co  m*/
        this.resourceFile = resource.getFile().toPath();
        Path parent = resourceFile.getParent();
        this.watchService = parent.getFileSystem().newWatchService();
        this.watchKey = parent.register(this.watchService, StandardWatchEventKinds.ENTRY_MODIFY,
                StandardWatchEventKinds.ENTRY_CREATE);
    } catch (IOException e) {
        throw new ConfigurationException(
                String.format("Failed to initialize watcher for resource '%s'", resource.toString()), e);
    }
}