Monitor Directory Changes Example
This program demonstrates monitoring a directory for changes.
Problem Statement
Write a Java program that monitors a directory for file creation, deletion, and modification using WatchService API.
Source Code
| 1 | import java.nio.file.*; |
| 2 | public class WatchServiceExample { |
| 3 | public static void main(String[] args) throws Exception { |
| 4 | System.out.println("Eduinq WatchService Example"); |
| 5 | WatchService ws=FileSystems.getDefault().newWatchService(); |
| 6 | Path path=Paths.get("C:/Eduinq"); |
| 7 | path.register(ws,StandardWatchEventKinds.ENTRY_CREATE, |
| 8 | StandardWatchEventKinds.ENTRY_DELETE, |
| 9 | StandardWatchEventKinds.ENTRY_MODIFY); |
| 10 | while(true){ |
| 11 | WatchKey key=ws.take(); |
| 12 | for(WatchEvent<?> event:key.pollEvents()){ |
| 13 | System.out.println("Eduinq Event: "+event.kind()+" File: "+event.context()); |
| 14 | } |
| 15 | key.reset(); |
| 16 | } |
| 17 | } |
| 18 | } |
Program Output
Eduinq WatchService Example Eduinq Event: ENTRY_CREATE File: test.txt Eduinq Event: ENTRY_MODIFY File: test.txt
Explanation
Registers directory with WatchService. - Monitors create, delete, modify events. - Exception handling ensures safe operations. - In enterprise systems, monitoring detects unauthorized changes. Conclusion: Shows monitoring directory changes.