1. 程式人生 > >使用WatchService監控資料夾

使用WatchService監控資料夾

通過java7提供的WatchService API 實現對資料夾的監控

package service;

import config.Config;
import java.io.IOException;
import java.nio.file.*;
import java.util.List;
import java.util.concurrent.TimeUnit;

public class WatchDirService {
    private WatchService watchService;
    private boolean notDone = true;

    public WatchDirService(String dirPath){
        init(dirPath);
    }

    private void init(String dirPath) {
        Path path = Paths.get(dirPath);
        try {
            watchService = FileSystems.getDefault().newWatchService();  //建立watchService
            path.register(watchService, 
            StandardWatchEventKinds.ENTRY_CREATE,
            StandardWatchEventKinds.ENTRY_MODIFY,
            StandardWatchEventKinds.ENTRY_DELETE); //註冊需要監控的事件,ENTRY_CREATE 檔案建立,ENTRY_MODIFY 檔案修改,ENTRY_MODIFY 檔案刪除
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public void start(){
        System.out.print("watch...");
        while (notDone){
            try {
                WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS); 
                if(watchKey != null){
                    List<WatchEvent<?>> events = watchKey.pollEvents();  //獲取所有得事件
                    for (WatchEvent event : events){
                        WatchEvent.Kind<?> kind = event.kind(); 
                        if (kind == StandardWatchEventKinds.OVERFLOW){
                            //當前磁碟不可用
                            continue;
                        }
                        WatchEvent<Path> ev = event;
                        Path path = ev.context();
                        if(kind == StandardWatchEventKinds.ENTRY_CREATE){
                            System.out.println("create " + path.getFileName());
                        }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
                            System.out.println("modify " + path.getFileName());
                        }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
                            System.out.println("delete " + path.getFileName());
                        }
                    }
                    if(!watchKey.reset()){ 
                        //已經關閉了程序
                        System.out.println("exit watch server");
                        break;
                    }
                }
            } catch (InterruptedException e) {
                e.printStackTrace();
                return;
            }
        }
    }
}

作者:DrJasonZhang 連結:https://www.jianshu.com/p/928ce1010407 來源:簡書 簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。