Showing posts with label file change event. Show all posts
Showing posts with label file change event. Show all posts

Monday, September 26, 2016

File Change Listener Implementation Using Java


package com.pritom.kumar;

import java.io.File;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

/**
 * Created by pritom on 25/09/2016.
 */
public class ChangeFileListener {
    public static void main(String[] args) throws Exception {
        startWatch("C:/tmp");
    }

    public static void startWatch(String location) {
        try {
            Path directory = Paths.get(location);
            println("Start listening directory: [" + location + "]");
            final WatchService watchService = directory.getFileSystem().newWatchService();
            directory.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);

            while (true) {
                final WatchKey watchKey = watchService.take();
                handleWatchTriggered(location, watchKey);
                boolean valid = watchKey.reset();
                if (!valid) {
                    throw new Exception("Watcher failed for listen [" + location + "]");
                }
            }
        }
        catch (Exception ex) {
            ex.printStackTrace();
        }
    }

    private static void handleWatchTriggered(String location, WatchKey watchKey) throws Exception {
        List<WatchEvent<?>> watchEventList = watchKey.pollEvents();
        for (WatchEvent watchEvent : watchEventList) {
            if (watchEvent.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                println("Created: [" + watchEvent.context().toString() + "]");
                File fileCreated = new File(location + "/" + watchEvent.context().toString());
            }
            else if (watchEvent.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                println("Deleted: [" + watchEvent.context().toString() + "]");
            }
            else if (watchEvent.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                println("Modified: [" + watchEvent.context().toString() + "]");
            }
        }
    }

    public static void println(Object o) {
        System.out.println("" + o);
    }
}