← Back to Advanced Java Course | Chapter 13: Java NIO | Lesson 4 of 5

Java का WatchService

WatchService किसी program को manually बार-बार poll करने के बजाय किसी directory पर creation, deletion, या modification जैसे file system बदलावों के लिए monitor करने देता है।

What is WatchService?

WatchService, NIO.2 का हिस्सा, किसी program को किसी directory के contents को manually बार-बार poll करने के बजाय creation, deletion, या modification जैसे file system बदलावों के लिए monitor करने देता है।

उदाहरण: What is WatchService?

java
import java.nio.file.*;
public class Main {
	public static void main(String[] args) throws Exception {
		WatchService watcher = FileSystems.getDefault().newWatchService(); // no manual polling needed
		System.out.println("WatchService created");
		watcher.close();
	}
}

Registering a Directory

किसी directory को उसके Path पर register call करके monitor किया जाता है, WatchService और ENTRY_CREATE, ENTRY_DELETE, या ENTRY_MODIFY जैसे specific kinds of events को पास करते हुए जिन पर नज़र रखनी है।

उदाहरण: Registering a Directory

java
// Import java.nio.file.* so it can be used by its short name
import java.nio.file.*;
// Import java.nio.file.StandardWatchEventKinds.* so it can be used by its short name
import static java.nio.file.StandardWatchEventKinds.*;
// Define the class Main
public class Main {
	// Program entry point: the JVM starts running here
	public static void main(String[] args) throws Exception {
		Path dir = Files.createTempDirectory("watch-demo");
		WatchService watcher = FileSystems.getDefault().newWatchService();
		dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
		// Print a line to the console
		System.out.println("Registered " + dir);
		watcher.close();
	}
}

Watching for File Creation

किसी WatchService पर take() call करना तब तक block करता है जब तक कोई registered event असल में न हो जाए, और returned WatchKey का pollEvents method फिर हर matching event return करता है जो इसके पिछले check होने के बाद हुआ हो।

उदाहरण: Watching for File Creation

java
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Path dir = Files.createTempDirectory("watch-demo");
		WatchService watcher = FileSystems.getDefault().newWatchService();
		dir.register(watcher, ENTRY_CREATE);
		Files.createFile(dir.resolve("new.txt"));
		WatchKey key = watcher.take(); // blocks until the event occurs
		for (WatchEvent<?> event : key.pollEvents()) {
			System.out.println(event.kind() + " " + event.context());
		}
		watcher.close();
	}
}

Watching for Modification and Deletion

ENTRY_MODIFY तब report करता है जब किसी मौजूदा file का content बदलता है और ENTRY_DELETE तब report करता है जब कोई file हटाई जाती है, किसी program को बिल्कुल किस तरह का file system बदलाव हुआ इसके आधार पर अलग react करने देते हुए।

उदाहरण: Watching for Modification and Deletion

java
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Path dir = Files.createTempDirectory("watch-demo");
		Path file = Files.createFile(dir.resolve("data.txt"));
		WatchService watcher = FileSystems.getDefault().newWatchService();
		dir.register(watcher, ENTRY_MODIFY, ENTRY_DELETE);
		Files.writeString(file, "changed"); // triggers ENTRY_MODIFY
		WatchKey key = watcher.take();
		for (WatchEvent<?> event : key.pollEvents()) {
			System.out.println(event.kind());
		}
		watcher.close();
	}
}

Processing Watch Events in a Loop

WatchService का एक typical उपयोग एक infinite loop है जो events का इंतज़ार करने के लिए take() call करता है, हर एक को process करता है, और फिर key पर reset() call करता है ताकि यह उसी directory पर future events report करना जारी रख सके।

उदाहरण: Processing Watch Events in a Loop

java
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class Main {
	public static void main(String[] args) throws Exception {
		Path dir = Files.createTempDirectory("watch-demo");
		WatchService watcher = FileSystems.getDefault().newWatchService();
		dir.register(watcher, ENTRY_CREATE);
		Files.createFile(dir.resolve("a.txt"));
		WatchKey key = watcher.take();
		for (WatchEvent<?> event : key.pollEvents()) {
			System.out.println("Event: " + event.kind());
		}
		key.reset(); // continues reporting future events
		watcher.close();
	}
}
Related Topics
{# common_mistakes/chapter_summary/browser_support: on Hindi pages the view already swaps in the hi_ translation fields (or blanks these out if untranslated), so this renders correctly for both languages without a lang_code check here. #}
आम गलतियां
  1. events process करने के बाद key.reset() call न करना, जिससे key बाद के events देना बंद कर देता है।
  2. event के context path को सीधे उपयोग करना, जबकि यह सिर्फ watched folder के relative file name है; इसे directory के खिलाफ resolve करें।
  3. हर save पर एक event की उम्मीद करना, जबकि editors अक्सर एक file के लिए कई ENTRY_MODIFY events पैदा करते हैं।
🔒

Chapter Quiz — Complete all 5 topics to unlock

0/5 topics done

Complete these topics first:

Login to run this code

C/C++/Java/PHP execution requires a free account. Your code is saved — you'll land right back in the editor after logging in.