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

来源:互联网 发布:小米电视ktv软件 编辑:程序博客网 时间:2024/05/17 07:44

我们用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.StandardWatchEventKinds.*;

/**
 * @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 e = (WatchEvent)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  

 

此代码已调试通过,如果本机默认的JDK版本不是7时,需要修改上面2的运行程序方法为:

java -version:1.7.0 TestWatcherService c:\test

原创粉丝点击