探秘JDK7新特性之監(jiān)聽文件系統(tǒng)的更改
我們用IDE(例如Eclipse)編程,外部更改了代碼文件,IDE馬上提升“文件有更改”。Jdk7的NIO2.0也提供了這個功能,用于監(jiān)聽文件系統(tǒng)的更改。它采用類似觀察者的模式,注冊相關(guān)的文件更改事件(新建,刪除……),當事件發(fā)生的,通知相關(guān)的監(jiān)聽者。
java.nio.file.*包提供了一個文件更改通知API,叫做Watch Service API.
實現(xiàn)流程如下
1.為文件系統(tǒng)創(chuàng)建一個WatchService 實例 watcher
2.為你想監(jiān)聽的目錄注冊 watcher。注冊時,要注明監(jiān)聽那些事件。
3.在無限循環(huán)里面等待事件的觸發(fā)。當一個事件發(fā)生時,key發(fā)出信號,并且加入到watcher的queue
4.從watcher的queue查找到key,你可以從中獲取到文件名等相關(guān)信息
5.遍歷key的各種事件
6.重置 key,重新等待事件
7.關(guān)閉服務(wù)
Java代碼
- 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
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("請設(shè)置要監(jiān)聽的文件目錄作為參數(shù)");
- 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
【編輯推薦】