Java IO Tutorial - Java WatchService.poll(long timeout, TimeUnit unit)


WatchService.poll(long timeout, TimeUnit unit) has the following syntax.

WatchKey poll(long timeout,  TimeUnit unit)  throws InterruptedException


In the following code shows how to use WatchService.poll(long timeout, TimeUnit unit) method.

//from ww w.j  a v  a2 s .  com
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.TimeUnit;

class SecurityWatch {

    WatchService watchService;

    private void register(Path path, Kind<Path> kind) throws IOException {
        path.register(watchService, kind);

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

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

        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!");
            } else {

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

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

                    if (kind == StandardWatchEventKinds.OVERFLOW) {

                    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) {


public class Main {

    public static void main(String[] args) {

        final Path path = Paths.get("C:/security");
        SecurityWatch watch = new SecurityWatch();

        try {
        } catch (IOException | InterruptedException ex) {