需要NIO2的基礎優~~我的Blog有基礎的一些教學也可以去java看教學!
作法如下
1 先建立一個你要監聽的對象如我想監聽src資料夾可以這麼做
Path path = Paths.get("..\\src");
2 建立一個WatchService,可由FileSystems.getDefault().newWatchService();取得建立時記得要try catch
3 將WatchService與需監聽的狀態 註冊到 Path上 程式碼如下
因為Path有實作Watchable介面才可註冊WatchService
try {
watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_DELETE);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
4 建立一個無窮迴圈他取得資料夾修改資訊watchService有三種方式可以取得修改資訊
1 poll 會返回WatchKey,如果沒有值會回傳null
2 poll(timeout, unit) 可指定等待時間返回WatchKey
3 take 如序列中沒資料時會wait也返回WatchKey
5 透過WatchKey當中的pollEvents 使用For回圈取得所有註冊狀態的回應
6 最後記得需要呼叫WatchKey的rest 將狀態變成Ready,不然會收不到新的訊息
7 你的的程序中可能會收到一個OVERFLOW事件,甚至如果該程序被沒有針對此事件註冊。
8 如果你註冊在根目錄其子目錄並不會有監聽效果!
7 你的的程序中可能會收到一個OVERFLOW事件,甚至如果該程序被沒有針對此事件註冊。
8 如果你註冊在根目錄其子目錄並不會有監聽效果!
程式下載
補充:
可監聽的狀態有:
補充:
可監聽的狀態有:
ENTRY_CREATE– A directory entry is created.ENTRY_DELETE– A directory entry is deleted.ENTRY_MODIFY– A directory entry is modified.OVERFLOW– Indicates that events might have been lost or discarded. You do not have to register for theOVERFLOWevent to receive it.
WatchKey的狀態
Readyindicates that the key is ready to accept events. When first created, a key is in the ready state.- path.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,這時會回傳WatchKey,此時的狀態事
Ready Signaledindicates that one or more events are queued. Once the key has been signaled, it is no longer in the ready state until theresetmethod is invoked.- WatchKey watchKey = watchService.take();透過watchService取的WatchKey因已經有Event在內的就變成了
Signaled Invalidindicates that the key is no longer active. This state happens when one of the following events occurs:
You do not need to specify the OVERFLOW event while registering a watchable with a WatchService to receive this event.
The counts for ENTRY_CREATE and ENTRY_DELETE are always 1.
This is as per the API description of these events. However, the count for ENTRY_MODIFY and OVERFLOW can be 1 or greater.The counts for ENTRY_CREATE and ENTRY_DELETE are always 1.
The count for ENTRY_MODIFY and OVERFLOW the count can be greater than 1. 可能會大於1
沒有留言:
張貼留言