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