Skip to content

Instantly share code, notes, and snippets.

@karmanov
Created October 16, 2013 13:55
Show Gist options
  • Save karmanov/7008142 to your computer and use it in GitHub Desktop.
Save karmanov/7008142 to your computer and use it in GitHub Desktop.
Monitor a Folder using Java
import java.io.IOException;
import java.nio.file.FileSystems;
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;
public class App04 {
public static void main(String[] args) throws IOException,
InterruptedException {
Path postFolder = Paths.get("D:\\test");
WatchService watchService = FileSystems.getDefault().newWatchService();
postFolder.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
boolean valid = true;
do {
WatchKey watchKey = watchService.take();
for (WatchEvent<?> event : watchKey.pollEvents()) {
if (StandardWatchEventKinds.ENTRY_CREATE.equals(event.kind())) {
String fileName = event.context().toString();
System.out.println("File Created: " + fileName);
}
if (StandardWatchEventKinds.ENTRY_MODIFY.equals(event.kind())) {
String fileName = event.context().toString();
System.out.println("File Modified: " + fileName);
}
if (StandardWatchEventKinds.ENTRY_DELETE.equals(event.kind())) {
String fileName = event.context().toString();
System.out.println("File Deleted: " + fileName);
}
}
valid = watchKey.reset();
} while (valid);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment