use the WatchService to monitor creation, deletion or modification of files on the home user directory - Java File Path IO

Java examples for File Path IO:WatchService

Description

use the WatchService to monitor creation, deletion or modification of files on the home user directory

Demo Code


import java.nio.file.*;
import java.util.Properties;



public class WatchServiceExample {

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

        Properties props = System.getProperties();
        String homePath = props.get("user.home").toString();
        Path home = fs.getPath(homePath);

        home.register(ws, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
                StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);

        System.out.println("Monitoring file creation in " + home + "... (Ctrl+C to quit)");
        while (true) {
            WatchKey key = ws.take();
            for (WatchEvent<?> event : key.pollEvents()) {
                if (event.kind() == StandardWatchEventKinds.ENTRY_CREATE) {
                    Path item = (Path)event.context();
                    System.out.println("Created: " + item);
                } else if (event.kind() == StandardWatchEventKinds.ENTRY_DELETE) {
                    Path item = (Path)event.context();
                    System.out.println("Removed: " + item);
                } else if (event.kind() == StandardWatchEventKinds.ENTRY_MODIFY) {
                    Path item = (Path)event.context();
                    System.out.println("Modified: " + item);
                } else {
                    Path item = (Path)event.context();
                    System.out.println("Else: " + item);
                }//from   ww w  .j a v a2  s  .  com
            }
            key.reset();
        }
    }
}

Related Tutorials