Monitor File Modification Example
This program demonstrates monitoring file modification events.
Problem Statement
Write a Java program that detects file modifications in a directory using WatchService API.
Source Code
| 1 | import java.nio.file.*; |
| 2 | public class FileModifyMonitor { |
| 3 | public static void main(String[] args) throws Exception { |
| 4 | System.out.println("Eduinq File Modify Monitor Example"); |
| 5 | WatchService ws=FileSystems.getDefault().newWatchService(); |
| 6 | Path path=Paths.get("C:/Eduinq"); |
| 7 | path.register(ws,StandardWatchEventKinds.ENTRY_MODIFY); |
| 8 | while(true){ |
| 9 | WatchKey key=ws.take(); |
| 10 | for(WatchEvent<?> event:key.pollEvents()){ |
| 11 | System.out.println("Eduinq File Modified: "+event.context()); |
| 12 | } |
| 13 | key.reset(); |
| 14 | } |
| 15 | } |
| 16 | } |
Program Output
Eduinq File Modify Monitor Example Eduinq File Modified: data.txt
Explanation
Registers only ENTRY_MODIFY event. - Detects file changes. - Exception handling ensures safe operations. - In enterprise systems, modification monitoring detects tampering. Conclusion: Shows monitoring file modification.