Friday, November 15, 2019

File Changes WatchService - When a file is updated in java


import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.stream.Collectors;

public class DirectoryWatchDemo {
public static void main(String[] args) {
try {
WatchService watcher = FileSystems.getDefault().newWatchService();
Path dir = Paths.get("D:\\WatchService");
dir.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
System.out.println("Watch Service registered for dir: " + dir.getFileName());
long initialCount = 0;
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException ex) {
return;
}

for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();

@SuppressWarnings("unchecked")
WatchEvent<Path> ev = (WatchEvent<Path>) event;
Path fileName = ev.context();

String filePath = dir.toString() + "\\" + fileName;

BufferedReader br1 = new BufferedReader(new FileReader(filePath));
long thisCount = br1.lines().count();
if (thisCount != 0) {

BufferedReader br2 = new BufferedReader(new FileReader(filePath));
System.out.println(br2.lines().skip(initialCount).collect(Collectors.toList()));
br2.close();
initialCount = thisCount;
}
br1.close();
/*
* if (kind == ENTRY_MODIFY &&
* fileName.toString().equals("DirectoryWatchDemo.java")) {
* System.out.println("My source file has changed!!!"); }
*/
}

boolean valid = key.reset();
if (!valid) {
break;
}
}

} catch (IOException ex) {
System.err.println(ex);
}
}
}

Output:
File in the Directory: D:\\WatchService\\ExampleText.txt

Watch Service registered for dir: WatchService
[Good Morning, How are you ?, Where are you going ?, When will you come?, GGood, Check, Good , Check, Show, Love You, Told you, Tuuu]
[]
[]
[Good]

Recent Post

Databricks Delta table merge Example

here's some sample code that demonstrates a merge operation on a Delta table using PySpark:   from pyspark.sql import SparkSession # cre...