Watch directory for modification in Java

Description

The following code shows how to watch directory for modification.

Example


import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
/*ww w.  java 2 s. com*/
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

public class Main {
  public static void main(String[] args) throws Exception {
    WatchService watcher = FileSystems.getDefault().newWatchService();

    Path dir = FileSystems.getDefault().getPath("c:/");

    WatchKey key = dir.register(watcher, ENTRY_MODIFY);

    while (true) {
      key = watcher.take();
      for (WatchEvent<?> event : key.pollEvents()) {
        if (event.kind() == ENTRY_MODIFY) {
          System.out.println("Home dir changed!");
        }
      }
      key.reset();
    }
  }
}




















Home »
  Java Tutorial »
    I/O »




Binary File
Byte Array
CharSet
Checksum
Console
Create Copy Move Delete
Directory
Drive
Encode Decode
File Attribute
File Lock
File System
GZIP
Jar File
NIO Buffer
Path
Scanner
StreamTokenizer
Temporary File
Text File
Zip