Watch Service NIO

package az.etibarli;

import java.io.IOException;
import java.nio.file.*;

public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
WatchService watchService = FileSystems.getDefault().newWatchService();
Path path = Paths.get("/Users/etibarliparvin/Desktop/Test2");

path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY);

System.out.println("Watching directory: " + path);

while (true) { // Infinite loop to keep watching
WatchKey key = watchService.take(); // Blocking call, waits for an event
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println("Event type: " + event.kind() +
" | File affected: " + event.context());
}
boolean valid = key.reset(); // Must be called to continue watching
if (!valid) {
System.out.println("Watch key is no longer valid.");
break; // Exit if the key is invalid
}
}
}

} 


===========================================================================

package az.etibarli;

import java.io.IOException;
import java.nio.file.*;

public class DirectoryWatcher implements Runnable {
private final Path directoryPath;

public DirectoryWatcher(String directory) {
this.directoryPath = Paths.get(directory);
}

@Override
public void run() {
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
directoryPath.register(watchService,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);

System.out.println("Watching directory: " + directoryPath);

while (true) {
WatchKey key = watchService.take(); // Blocks until an event occurs
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
Path filePath = (Path) event.context();
Path fullPath = directoryPath.resolve(filePath);

// Detect file creation
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("New file detected: " + fullPath);
if (fullPath.toString().endsWith(".txt")) {
MT103Reader.readMT103(fullPath.toString());
}
}

// Detect file modifications
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("File modified: " + fullPath);
if (fullPath.toString().endsWith(".txt")) {
System.out.println("Re-reading updated file...");
MT103Reader.readMT103(fullPath.toString());
}
}

// Detect file deletions
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("File deleted: " + fullPath);
}
}

boolean valid = key.reset(); // Reset key to continue watching
if (!valid) {
System.out.println("Watch key is no longer valid. Stopping watcher.");
break;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}

}



package az.etibarli;

import java.io.BufferedReader;
import java.io.FileReader;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;

public class MT103Reader {

public static void readMT103(String filename) {
Map<String, String> mt103Fields = new LinkedHashMap<>();
String currentKey = null;

try (BufferedReader br = new BufferedReader(new FileReader(filename))) {
String line;
while ((line = br.readLine()) != null) {
if (line.startsWith("{") || line.equals("-}")) continue;

if (line.startsWith(":")) {
String[] parts = line.split(":", 3);
if (parts.length == 3) {
currentKey = parts[1]; // Store key
mt103Fields.put(currentKey, parts[2]); // Store value
}
} else if (currentKey != null) {
// Append multi-line field content
mt103Fields.put(currentKey, mt103Fields.get(currentKey) + " " + line.trim());
}
}

System.out.println("Parsed MT103 Fields:");
mt103Fields.forEach((key, value) -> System.out.println(key + " -> " + value));

} catch (IOException e) {
e.printStackTrace();
}
}
}


package az.etibarli;

import java.io.IOException;
import java.nio.file.*;

public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
String directoryPath = "/Users/etibarliparvin/Desktop/Test2";

Thread watcherThread = new Thread(new DirectoryWatcher(directoryPath));
watcherThread.setDaemon(true);
watcherThread.start();

System.out.println("Directory watcher started. Waiting for new files...");

while (true) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
break;
}
}

}
}
























Комментарии

Популярные сообщения из этого блога

Lesson1: JDK, JVM, JRE

SE_21_Lesson_11: Inheritance, Polymorphism

Preparation for Java interview