package org.kodejava.io;
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class WatchServiceGetFilename {
public static void main(String[] args) {
try {
// Create a WatchService and register the logDir path with the
// WatchService for ENTRY_CREATE.
WatchService watcher = FileSystems.getDefault().newWatchService();
Path logDir = Paths.get("F:/Temp");
logDir.register(watcher, ENTRY_CREATE);
while (true) {
WatchKey key;
try {
key = watcher.take();
} catch (InterruptedException e) {
return;
}
for (WatchEvent<?> event : key.pollEvents()) {
if (event.kind() == ENTRY_CREATE) {
// Get the name of created file.
WatchEvent<Path> ev = cast(event);
Path filename = ev.context();
System.out.printf("A new file %s was created.%n",
filename.getFileName());
}
}
key.reset();
}
} catch (IOException e) {
e.printStackTrace();
}
}
@SuppressWarnings("unchecked")
private static <T> WatchEvent<T> cast(WatchEvent<?> event) {
return (WatchEvent<T>) event;
}
}
Tag Archives: WatchService
How to monitor file or directory changes?
package org.kodejava.io;
import java.io.IOException;
import java.nio.file.*;
import static java.nio.file.StandardWatchEventKinds.*;
public class FileWatchDemo {
public static void main(String[] args) {
try {
// Creates a instance of WatchService.
WatchService watcher = FileSystems.getDefault().newWatchService();
// Registers the logDir below with a watch service.
Path logDir = Paths.get("F:/Temp/");
logDir.register(watcher, ENTRY_CREATE, ENTRY_MODIFY, ENTRY_DELETE);
// Monitor the logDir at listen for change notification.
while (true) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (ENTRY_CREATE.equals(kind)) {
System.out.println("Entry was created on log dir.");
} else if (ENTRY_MODIFY.equals(kind)) {
System.out.println("Entry was modified on log dir.");
} else if (ENTRY_DELETE.equals(kind)) {
System.out.println("Entry was deleted from log dir.");
}
}
key.reset();
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
}
}
To get the created, modified or deleted file you can see the following example: How to get the file name when using WatchService?.
