我正在尝试评估我当前需要拦截给定目录及其子目录中的文件更改的需求。适合我需求的两个工具是jpathwatch和jnotify。jpathwatch可以工作,但不支持递归目录监视。Jnotify似乎很好地解决了这个限制。
在评估jnotify时,我观察到了一个奇怪的行为。这在linux和windows中都是一致的。让我试着用一个例子来解释。我有以下目录结构:
C:
|--> Temp |
| --> File |
| --> Dir |
| --> SubDirjNotify配置为侦听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相关的帖子,如果有人能提供一些建议或其他解决方案来解决这个问题,我将非常感激。
谢谢
发布于 2012-10-09 13:22:13
这很可能不是jNotify的问题,而是因为操作系统处理文件创建的方式。我在Python中看到过类似的事情发生在pynofity库中。您应该在应用程序代码中处理此问题,比如将触发器处理延迟几秒,这样您就可以缓冲任何新事件,然后只处理某个类型的最新事件。
https://stackoverflow.com/questions/12793062
复制相似问题