Escucha de directorio en Java

Tengo una aplicación en la que quiero escuchar cualquier cambio realizado en un directorio en particular. La aplicación debe hacerme un ping tan pronto como haya archivos agregados, eliminados o actualizados en ese directorio.

Puedes usar JNotify

JNotify es una biblioteca de Java que permite a la aplicación Java escuchar eventos del sistema de archivos, tales como: Archivo creado Archivo modificado Archivo renombrado Archivo eliminado Plataformas compatibles

Windows (2000 o más reciente) Notas de Windows Linux con soporte de INofity (2.6.14 o posterior) Notas de Linux Mac OS X (10.5 o posterior) Notas de Mac OS

Más información :

Descargue JNotify desde aquí

Extraiga el zip, ponga .dll / .so según la plataforma en su ruta de lib. y crea una clase que proporcione jnotify-0.93.jar en la ruta de la clase.

Código de muestra:

 package org.life.java.stackoverflow.questions; import net.contentobjects.jnotify.JNotify; import net.contentobjects.jnotify.JNotifyListener; /** * * @author Jigar */ public class JNotifyDemo { public void sample() throws Exception { // path to watch String path = System.getProperty("user.home"); // watch mask, specify events you care about, // or JNotify.FILE_ANY for all events. int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; // watch subtree? boolean watchSubtree = true; // add actual watch int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener()); // sleep a little, the application will exit if you // don't (watching is asynchronous), depending on your // application, this may not be required Thread.sleep(1000000); // to remove watch the watch boolean res = JNotify.removeWatch(watchID); if (!res) { // invalid watch ID specified. } } class Listener implements JNotifyListener { public void fileRenamed(int wd, String rootPath, String oldName, String newName) { print("renamed " + rootPath + " : " + oldName + " -> " + newName); } public void fileModified(int wd, String rootPath, String name) { print("modified " + rootPath + " : " + name); } public void fileDeleted(int wd, String rootPath, String name) { print("deleted " + rootPath + " : " + name); } public void fileCreated(int wd, String rootPath, String name) { print("created " + rootPath + " : " + name); } void print(String msg) { System.err.println(msg); } } public static void main(String[] args) throws Exception { new JNotifyDemo().sample(); } } 

Salida:

 modified C:\Documents and Settings\jigar: LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_4s8ywsvyukghK0uDxRop modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119 modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea9 created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eae modified C:\Documents and Settings\jigar : LOCALS~1\Temp\output1295531079119 modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Current Session deleted C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001ea8 created C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom modified C:\Documents and Settings\jigar : LOCALS~1\Temp\etilqs_04gchL79ZJrpClZIqiom modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf modified C:\Documents and Settings\jigar : Local Settings\Application Data\Google\Chrome\User Data\Default\Cache\f_001eaf 

Desde Java 1.7 puede usar la API Watch Service para registrarse para eventos de directorio. Es parte de la nueva biblioteca de E / S (NIO) de Java y no requiere ningún recurso adicional. Un ejemplo de cómo usar la API se puede encontrar en la documentación oficial .

Después de registrar WatchService, puede recuperar eventos para la ruta de destino de esta manera:

 for (WatchEvent< ?> event: key.pollEvents()) { // Context for directory entry event is the file name of entry WatchEvent ev = cast(event); Path name = ev.context(); Path child = dir.resolve(name); // print out event System.out.format("%s: %s\n", event.kind().name(), child); } 

Jnotify para notificaciones de archivos en java. Muestra de código

  public void sample() throws Exception { // path to watch String path = System.getProperty("user.home"); // watch mask, specify events you care about, // or JNotify.FILE_ANY for all events. int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED; // watch subtree? boolean watchSubtree = true; // add actual watch int watchID = JNotify.addWatch(path, mask, watchSubtree, new Listener()); // sleep a little, the application will exit if you // don't (watching is asynchronous), depending on your // application, this may not be required Thread.sleep(1000000); // to remove watch the watch boolean res = JNotify.removeWatch(watchID); if (!res) { // invalid watch ID specified. } } class Listener implements JNotifyListener { public void fileRenamed(int wd, String rootPath, String oldName, String newName) { print("renamed " + rootPath + " : " + oldName + " -> " + newName); } public void fileModified(int wd, String rootPath, String name) { print("modified " + rootPath + " : " + name); } public void fileDeleted(int wd, String rootPath, String name) { print("deleted " + rootPath + " : " + name); } public void fileCreated(int wd, String rootPath, String name) { print("created " + rootPath + " : " + name); } void print(String msg) { System.err.println(msg); } }