Filter WatchService Events Example

This program demonstrates filtering WatchService events.

Problem Statement

Write a Java program that filters WatchService events to only log .txt file changes.

Source Code

1 import java.nio.file.*;
2 public class WatchServiceFilterExample {
3 public static void main(String[] args) throws Exception {
4 System.out.println("Eduinq WatchService Filter 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 Path file=(Path)event.context();
14 if(file.toString().endsWith(".txt")){
15 System.out.println("Eduinq Event: "+event.kind()+" File: "+file);
16 }
17 }
18 key.reset();
19 }
20 }
21 }

Program Output

					Eduinq WatchService Filter Example
Eduinq Event: ENTRY_CREATE File: notes.txt
				

Explanation

Filters events by file extension. - Logs only .txt file changes. - Exception handling ensures safe operations. - In enterprise systems, filtering reduces noise in monitoring logs. Conclusion: Shows filtering WatchService events.

Quick Links to Explore