JNotify 监听文件夹 java监听文件夹

下载链接: http://jnotify.sourceforge.net/index.html官网地址
解压 吧dll文件放入jre bin 目录(linux )
在这里插入图片描述
在这l里插入图片描述 linux放这个
导入坐标

 <dependency>
            <groupId>net.contentobjects.jnotify</groupId>
            <artifactId>jnotify</artifactId>
            <version>0.94</version>
        </dependency>

实现对文件目录的监听

import java.io.File;

import net.contentobjects.jnotify.JNotify;

public class FileNotify {
    public static void notify(String filepath) throws Exception {
        if (!new File(filepath).exists()) {
            System.out.println("文件目录不存在");
            return;
        }

        // 定义你所需要检测的事件类型,或者是全部FILE_ANY
        int mask = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
        int mask1 =JNotify.FILE_ANY;
        // 是否检测子目录
        boolean watchSubtree = true;
        // 添加监听
        int watchID = JNotify.addWatch(filepath, mask, watchSubtree, new Listener());
        System.out.println(watchID);
        // 定义监听持续时间,此处是死循环,所以是时刻监听
//      while(true) {
//          Thread.sleep(1000*60);
//      }

        // 定义监听时间,如果超过这个时间,程序会退出;如果不定义就得不到监听
        Thread.sleep(1000*60);//60秒

        //移除监听
        boolean res = JNotify.removeWatch(watchID);
        if (!res) {
          // invalid watch ID specified.
        }

    }

    public static void main(String[] args) {
        String path ="F:\\Pm25";
        System.out.println(path);
        try {
            notify(path);
        } catch (Exception e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    }
}

监听事件的处理

			class Listener implements JNotifyListener {
			    public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
			        System.out.println(wd);
			        System.out.println(rootPath);
			        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
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值