Monitorare il file system con Java
Finalmente vacanza, e finalmente posso dedicarmi di più al blog e alla programmazione per conto mio!
Oggi vediamo come monitorare il file system usando Java e il packaje NIO (incluso nel JDK ovviamente).
Qui potete leggere le differenze rispetto al più classico IO.
Partiamo dal main:
import java.io.IOException;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.ENTRY_MODIFY;
import static java.nio.file.StandardWatchEventKinds.ENTRY_DELETE;
public class Main {
public static void main(String[] args) throws IOException, InterruptedException {
Path folder = Paths.get("/path/to/dir");
if (folder == null) {
throw new UnsupportedOperationException("Directory not found");
}
WatchService ws = folder.getFileSystem().newWatchService();
Watcher w = new Watcher(ws);
Thread th = new Thread(w, "Watcher");
th.start();
folder.register(ws, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
th.join();
}
}
Come vedete usiamo praticamente solo classi e oggetti di NIO.
Watcher è la classe che implementeremo, e che richiede un oggetto WatchService.
Sotto, al metodo register, indichiamo tutti gli eventi che vogliamo registrare (in questo caso creazione, cancellazione e modifica di file).
A questo punto la classe Watcher:
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class Watcher implements Runnable {
private final WatchService watchService;
public Watcher(WatchService ws) {
this.watchService = ws;
}
@Override
public void run() {
try {
WatchKey key = watchService.take();
while (key != null) {
for (WatchEvent event : key.pollEvents()) {
System.out.printf("Received %s event for file: %s\n", event.kind(), event.context());
}
key.reset();
key = watchService.take();
}
} catch (InterruptedException ex) {
System.out.println(ex.getMessage());
}
System.out.println("Stopping thread");
}
}
Come vedete implementiamo l'interfaccia Runnable.
In questo modo non blocchiamo mai il processo principale, e possiamo ricevere tutte le modifiche in tempo reale.
Testato con Java 7, ma penso che funzioni bene anche con Java 8.
Bene, direi che è tutto!
Enjoy!
java jdk nio runnable watchservice watcher register
Commentami!