Log WatchService Events Example

This program demonstrates logging WatchService events to a file.

Problem Statement

Write a Java program that logs WatchService events into a log file.

Source Code

1 import java.nio.file.*;
2 import java.io.*;
3 public class WatchServiceLogExample {
4 public static void main(String[] args) throws Exception {
5 System.out.println("Eduinq WatchService Log Example");
6 WatchService ws=FileSystems.getDefault().newWatchService();
7 Path path=Paths.get("C:/Eduinq");
8 path.register(ws,StandardWatchEventKinds.ENTRY_CREATE,
9 StandardWatchEventKinds.ENTRY_DELETE,
10 StandardWatchEventKinds.ENTRY_MODIFY);
11 try(PrintWriter pw=new PrintWriter(new FileWriter("monitor.log",true))){
12 while(true){
13 WatchKey key=ws.take();
14 for(WatchEvent<?> event:key.pollEvents()){
15 pw.println("Eduinq Event: "+event.kind()+" File: "+event.context());
16 pw.flush();
17 }
18 key.reset();
19 }
20 }
21 }
22 }

Program Output

					Eduinq WatchService Log Example
(Log file entries created)
				

Explanation

Logs events into monitor.log. - Provides persistent audit trail. - Exception handling ensures safe operations. - In enterprise systems, logging supports compliance and auditing. Conclusion: Shows logging WatchService events.

Quick Links to Explore