Java Directory Listener
In Java 7 you can use java.nio.file package that to listen directory change events. In this example you will see how to create Java directory listener which will listen supported StandardWatchEventKinds event types below:
- ENTRY_CREATE – Directory entry is created
- ENTRY_DELETE – Directory entry is deleted
- ENTRY_MODIFY – Directory entry is modified
- OVERFLOW – Indicates which events might have been lost or discarded. We do not have to register for OVERFLOW event to receive it.
As I have tested in windows environment same can be use in Linux as well only you will have change path of the file.
- JavaDirectoryChangeListener.java:
package com.javahonk; import java.nio.file.FileSystems; import java.nio.file.Path; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchKey; import java.nio.file.WatchService; public class JavaDirectoryChangeListener implements Runnable { private static Path directoryPath; public static void main(String[] args) { directoryPath = FileSystems.getDefault().getPath("C:\\JavaHonk\\New folder"); Thread thread = new Thread(new JavaDirectoryChangeListener()); thread.start(); } @Override public void run() { try { WatchService watchService = directoryPath.getFileSystem().newWatchService(); directoryPath.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); //Start infinite loop to watch changes on the directory while (true) { WatchKey watchKey = watchService.take(); // poll for file system events on the WatchKey for (final WatchEvent<?> event : watchKey.pollEvents()) { //Calling method takeActionOnChangeEvent(event); } //Break out of the loop if watch directory got deleted if (!watchKey.reset()) { watchKey.cancel(); watchService.close(); System.out.println("Watch directory got deleted. Stop watching it."); //Break out from the loop break; } } } catch (InterruptedException interruptedException) { System.out.println("Thread got interrupted:"+interruptedException); return; } catch (Exception exception) { exception.printStackTrace(); return; } } private void takeActionOnChangeEvent(WatchEvent<?> event) { Kind<?> kind = event.kind(); if (kind.equals(StandardWatchEventKinds.ENTRY_CREATE)) { Path entryCreated = (Path) event.context(); System.out.println("New entry created:" + entryCreated); } else if (kind.equals(StandardWatchEventKinds.ENTRY_DELETE)) { Path entryDeleted = (Path) event.context(); System.out.println("Exissting entry deleted:" + entryDeleted); } else if (kind.equals(StandardWatchEventKinds.ENTRY_MODIFY)) { Path entryModified = (Path) event.context(); System.out.println("Existing entry modified:"+ entryModified); } } }
- Output:
- For more information please visit Oracle documentation here