2011-02-09 15 views
17

Tengo una aplicación en la que deseo 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.Oyente de directorio en Java

Respuesta

21

Puede utilizar JNotify

JNotify es una biblioteca de Java que permite la aplicación java para escuchar a presentar eventos del sistema, tales como: El archivo creado del archivo modificado archivo renombrado suprimido compatibles plataformas

Windows (2000 o posterior) Notas de Windows Linux con soporte INofity (2.6.14 o más reciente) Notas de Linux Mac OS X (1 0.5 o más reciente ) Mac OS señala

Más información:

Descargar JNotify de here

Extracto de la cremallera, puesto .dll/.so según la plataforma en su camino lib. y crea una clase proporciona jnotify-0.93.jar en la ruta de la clase.

Código de ejemplo:

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 
+11

* Downvoters * por favor comente –

+1

Cuando ejecuto el programa me da exceptionError loading library, java.library.path = C : \ Archivos de programa \ Java \ jdk1.7.0 \ bin;.; C: \ Windows \ Sun \ Java \ bin; C: \ Windows \ system32; C: \ Windows; C: \ Windows; C: \ Windows \ system32; C: \ Windows \ system32 \ Wbem; \ WindowsPowerShell \ v1.0 \; C: \ Archivos de programa \ Microsoft SQL Server \ 90 \ Tools \ binn \; C: \ apache-tomcat-6.0.26 \ bin; C: \ Archivos de programa \ Java \ jdk1.7.0 \ bin; C: \ Archivos de programa \ TortoiseSVN \ bin; C: \ Archivos de programa \ masilla; C: \ Archivos de programa \ Google \ Chrome \ Aplicación; C: \ Archivos de programa \ Java \ jdk1.7.0 \ include Excepción en el hilo "main" java.lang.Unsa – Jinith

+0

'Extraiga el zip, ponga .dll/.so de acuerdo con la plataforma en su ruta de acceso lib. –

3

Jnotificar para notificación de archivos en java. Ejemplo 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); } 
     } 
+0

cuando corro el programa me da la carga de bibliotecas exceptionError, java.library.path = C: \ Archivos de programa \ Java \ jdk1.7.0 \ bin;.; C: \ Windows \ Sun \ Java \ bin; C: \ Windows \ system32; C: \ Windows; C: \ Windows; C: \ Windows \ system32; C: \ Windows \ system32 \ Wbem; \ WindowsPowerShell \ v1.0 \; C: \ Archivos de programa \ Microsoft SQL Server \ 90 \ Tools \ binn \; C: \ apache-tomcat-6.0.26 \ bin; C: \ Archivos de programa \ Java \ jdk1 .7.0 \ bin; C: \ Archivos de programa \ TortoiseSVN \ bin; C: \ Archivos de programa \ masilla; C: \ Archivos de programa \ Google \ Chrome \ Aplicación; C: \ Archivos de programa \ Java \ jdk1.7.0 \ include Excepción en el hilo "principal" java.lang.Unsa – Jinith

+0

1.- Haga clic con el botón derecho en el Proyecto 2.- Propiedades 3.- Haga clic en EJECUTAR 4.- Opciones de VM: java -Djava.library.path = "your_path" 5.- por ejemplo en mi caso: java -Djava.library.path = 6.- Ok –

20

Desde Java 1.7 se puede utilizar el Watch Service API para inscribirse en los eventos de directorio. Es parte de la biblioteca New I/O (NIO) de Java y no requiere ningún recurso adicional. Un ejemplo de cómo usar la API se puede encontrar en el official documentation.

Después de registrar el 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<Path> 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); 
     }