2012-10-09 55 views
1

我试图评估当前需要拦截给定目录及其子目录中的文件更改的需求。适合我需求的几个工具是jpathwatch和jnotify。 jpathwatch的工作原理,但不支持递归目录监视。 Jnotify似乎很好地解决了这个限制。对新文件jNotify的奇怪行为

在评估jnotify时,我观察到一个奇怪的行为。这在Linux和Windows中都是一致的。让我试着用一个例子来解释。我有以下目录结构:


C: 
|--> Temp | 
      | --> File | 
        | --> Dir | 
           | --> SubDir 

jNotify配置为侦听C:/ Temp/File。现在,如果我在“Dir”或“SubDir”文件夹下放置文件,它将捕获新创建的事件。但是,在同一时间,提出了三个文件修改事件。当我在“SubDir”文件夹中添加一个新文件Extraction.log时,输出如下。


created C:/Temp/File/Dir/SubDir/Extraction.log 
modified C:/Temp/File/Dir/SubDir/Extraction.log 
modified C:/Temp/File/Dir/SubDir/Extraction.log 
modified C:/Temp/File/Dir/SubDir/Extraction.log 

正如你所看到的,文件修改有3个事件。该应用程序没有任何方法来确定其修改或新文件创建。所以,它会处理相同的文件四次。

我使用JNotify网站中显示的示例代码。


package com.test.io; 

import net.contentobjects.jnotify.JNotify; 

public class JNotifyTest { 

    /** 
    * @param args 
    */ 
    public static void main(String[] args) { 
     JNotifyTest jNotify = new JNotifyTest(); 
     try { 
      jNotify.sample(); 
     } catch (Exception e) { 
      // TODO Auto-generated catch block 
      e.printStackTrace(); 
     } 
    } 

    private void sample() throws Exception { 
     // path to watch 

     String path = "C:\\Temp\\File\\"; 

     // 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) { 
      System.out.println("renamed " + rootPath + oldName + " -> " + newName); 
     } 
     public void fileModified(int wd, String rootPath, String name) { 
      System.out.println("modified " + rootPath + name); 
     } 
     public void fileDeleted(int wd, String rootPath, String name) { 
      System.out.println("deleted " + rootPath + name); 
     } 
     public void fileCreated(int wd, String rootPath, String name) { 
      System.out.println("created " + rootPath + name); 
     } 
    } 
} 

不幸的是,我不能使用jdk 1.7,因为我们被困在1.6中。

我见过很多与jNotify相关的帖子,如果有人可以提供指针或任何其他解决方案来解决这个需求,我会非常感激。

感谢

回答

0

这是最有可能不是jNotify问题,但由于方式的OS处理文件的创建。我在Python中看到类似的事情发生在pynofity库中。您应该在应用程序代码中处理此问题,例如将触发处理延迟几秒钟,以便可以缓冲任何新事件(如果有),然后仅处理某个类型的最新事件。

+0

感谢您的回复。正如你所提到的,它可能是一个操作系统的问题,它引发了文件创建或修改的多个事件。但是,我不确定你提出的缓冲解决方案将如何工作,特别是当连续处理多个文件时。 – Shamik