Monitor File Changes

https://www.notion.so/Monitor-File-Changes-0d635ecd452c4e5eb7ad13f9777adafe

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
public static void main(String[] args) throws Exception {
 
   WatchService watchService = FileSystems.getDefault().newWatchService();

   Path path = Paths.get("G:\\");

   path.register(
       watchService,
       StandardWatchEventKinds.ENTRY_CREATE,
       StandardWatchEventKinds.ENTRY_DELETE,
       StandardWatchEventKinds.ENTRY_MODIFY);

   WatchKey key;
   while ((key = watchService.take()) != null) {
       for (WatchEvent<?> event : key.pollEvents()) {
          System.out.println("Event:" + event.kind() + ", File:" + event.context());
       }
       key.reset();
   }
}

WatchService added in Java7 for NIO solution.

This post is licensed under CC BY 4.0 by the author.