JDK7新特性 监听文件系统的更改

我们用IDE(例如Eclipse)编程,外部更改了代码文件,IDE马上提升“文件有更改”。Jdk7的NIO2.0也提供了这个功能,用于监听文件系统的更改。它采用类似观察者的模式,注册相关的文件更改事件(新建,删除……),当事件发生的,通知相关的监听者。

 

java.nio.file.*包提供了一个文件更改通知API,叫做Watch Service API.

 

实现流程如下

 

1.为文件系统创建一个WatchService 实例 watcher

2.为你想监听的目录注册 watcher。注册时,要注明监听那些事件。

3.在无限循环里面等待事件的触发。当一个事件发生时,key发出信号,并且加入到watcher的queue

4.从watcher的queue查找到key,你可以从中获取到文件名等相关信息

5.遍历key的各种事件

6.重置 key,重新等待事件

7.关闭服务

import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import static java.nio.file.StandardWatchEventKind.*;

/**
 * @author kencs@foxmail.com
 */
public class TestWatcherService {
    
    private WatchService watcher;
    
    public TestWatcherService(Path path)throws IOException{
        watcher = FileSystems.getDefault().newWatchService();
        path.register(watcher, ENTRY_CREATE,ENTRY_DELETE,ENTRY_MODIFY);
    }
    
    public void handleEvents() throws InterruptedException{
        while(true){
            WatchKey key = watcher.take();
            for(WatchEvent<?> event : key.pollEvents()){
                WatchEvent.Kind kind = event.kind();
                
                if(kind == OVERFLOW){//事件可能lost or discarded
                    continue;
                }
                
                WatchEvent<Path> e = (WatchEvent<Path>)event;
                Path fileName = e.context();
                
                System.out.printf("Event %s has happened,which fileName is %s%n"
                        ,kind.name(),fileName);
            }
            if(!key.reset()){
                break;
            }
        }
    }
    
    public static void main(String args[]) throws IOException, InterruptedException{
        if(args.length!=1){
            System.out.println("请设置要监听的文件目录作为参数");
            System.exit(-1);
        }
        new TestWatcherService(Paths.get(args[0])).handleEvents();
    }
}

接下来,见证奇迹的时刻

1.随便新建一个文件夹 例如 c:\\test
2.运行程序 java TestWatcherService c:\\test
3.在该文件夹下新建一个文件本件 “新建文本文档.txt
4.将上述文件改名为 abc.txt
5.打开文件,输入点什么吧,再保存。
6.Over!看看命令行输出的信息吧



Event ENTRY_CREATE has happened,which fileName is 新建文本文档.txt
Event ENTRY_DELETE has happened,which fileName is 新建文本文档.txt
Event ENTRY_CREATE has happened,which fileName is abc.txt
Event ENTRY_MODIFY has happened,which fileName is abc.txt
Event ENTRY_MODIFY has happened,which fileName is abc.txt


  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值