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