package org.testWatch.Watch;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
public class TestWatch {
public static void main(String[] args) {
try{
//創建一個監聽服務
WatchService service=FileSystems.getDefault().newWatchService();
//設置路徑
Path path=Paths.get("f://練練練");
//注冊監聽器
path.register(service, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
WatchKey watchKey;
//使用dowhile
do{
//獲取一個watch key
watchKey=service.take();
for(WatchEvent<?> event:watchKey.pollEvents()){
//如果時間列表不為空,打印事件內容
WatchEvent.Kind<?> kind=event.kind();
Path eventPath=(Path)event.context();
System.out.println(eventPath+":"+kind+":"+eventPath);
}
System.out.println("目錄內容發生改變");
}while(watchKey.reset());
}catch(Exception e){
e.printStackTrace();
}
// 1、通過FileSystems.getDefault().newWatchService()創建一個監聽服務;
// 2、設置路徑;
// 3、對目錄注冊一個監聽器;
// 4、之后進入循環,等待watch key;
// 5、此時如果有事件發生可通過watchkey的pollevent()方法獲取;
// 6、之后可以對event處理;
}
}