java监视器的移除,JAVA实时监控指定文件夹 创建文件,修改文件,删除文件

话不多说,直接上代码:

1 package com.python;

2 import java.nio.file.FileSystems;

3 import java.nio.file.Path;

4 import java.nio.file.Paths;

5 import java.nio.file.StandardWatchEventKinds;

6 import java.nio.file.WatchEvent;

7 import java.nio.file.WatchKey;

8 import java.nio.file.WatchService;

9 public class Watch {

10 public static void main(String[] args) {

11 try{

12

13 //创建一个监听服务

14 WatchService service=FileSystems.getDefault().newWatchService();

15 //设置路径

16 Path path=Paths.get("D:\\ATEST");

17 //注册监听器

18 path.register(service, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);

19

20 WatchKey watchKey;

21

22 //使用dowhile

23 do{

24 //获取一个watch key

25 watchKey=service.take();

26 for(WatchEvent> event:watchKey.pollEvents()){

27 //如果时间列表不为空,打印事件内容

28 WatchEvent.Kind> kind=event.kind();

29 Path eventPath=(Path)event.context();

30 System.out.println(eventPath+":"+kind+":"+eventPath);

31

32 }

33 System.out.println("目录内容发生改变");

34

35 }while(watchKey.reset());

36 }catch(Exception e){

37 e.printStackTrace();

38

39 }

40

41 // 1、通过FileSystems.getDefault().newWatchService()创建一个监听服务;

42 // 2、设置路径;

43 // 3、对目录注册一个监听器;

44 // 4、之后进入循环,等待watch key;

45 // 5、此时如果有事件发生可通过watchkey的pollevent()方法获取;

46 // 6、之后可以对event处理;

47 }

48 }

标签:文件,java,nio,Path,文件夹,file,import,JAVA,event

来源: https://www.cnblogs.com/smartisn/p/12846704.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值