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


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

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章