JNotify,一个支持动态监控文件和文件夹(支持级联监控)的架包。在linux系统中,调用的是linux底层的inotify服务,只是添加了对子文件夹级联监控的功能。在windows中,需要添加附件的dll文件,因为windows默认没有该服务,这是大拿们自己开发的一个功能。
使用很简单,以我的ubuntu系统为例:
1,将jnotify包引入到工程中。
2,将jnotify依赖的so文件加入到java.library.path路径中。这个变量可能会有多个位置,随便将jnotify压缩包中附带的libjnotify.so文件加入到其中的任何一个路径中即可。如果不知道这个变量的值,可以使用System.getProperty("java.library.path")查看。当然,如果不想这么麻烦,可以在启动程序时指定JVM的参数
,这样和上面将so文件加入系统路径中是一样的效果。
然后,写个测试类就可以看见效果了。
我这里没有自己写,只是简单的拷贝了一下JNotify官网的测试代码。
在实际的使用过程中,如果是web工程,我的习惯是添加一个listener监听器,当监听器初始化时,添加对指定文件或文件夹的监控。这样我们就不必为每次修改了配置文件都需要重启工程而苦恼了。如果是Java工程,就是需要的地方添加监控吧。
使用很简单,以我的ubuntu系统为例:
1,将jnotify包引入到工程中。
2,将jnotify依赖的so文件加入到java.library.path路径中。这个变量可能会有多个位置,随便将jnotify压缩包中附带的libjnotify.so文件加入到其中的任何一个路径中即可。如果不知道这个变量的值,可以使用System.getProperty("java.library.path")查看。当然,如果不想这么麻烦,可以在启动程序时指定JVM的参数
- -Djava.library.path=你的位置
然后,写个测试类就可以看见效果了。
我这里没有自己写,只是简单的拷贝了一下JNotify官网的测试代码。
- public class JnotifyTest {
- public static void main(String[] args) {
- try {
- new JnotifyTest().sample();
- } catch (Exception e) {
- e.printStackTrace();
- }
- // System.out.println(System.getProperty("java.library.path"));
- }
- 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);
- }
- }
- }
在实际的使用过程中,如果是web工程,我的习惯是添加一个listener监听器,当监听器初始化时,添加对指定文件或文件夹的监控。这样我们就不必为每次修改了配置文件都需要重启工程而苦恼了。如果是Java工程,就是需要的地方添加监控吧。