您的位置:首页 > 编程语言 > Java开发

jdk7监听文件系统变化通知新特性

2017-11-08 17:58 555 查看
2.1IO and New IO 监听文件系统变化通知   
  
通过FileSystems.getDefault().newWatchService()获取watchService,然后将需要监听的path目录注册到这个watchservice中,对于这个目录的文件修改,新增,删除等实践可以配置,然后就自动能监听到响应的事件。  
  
    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<Path> e = (WatchEvent<Path>) event;  
    Path fileName = e.context();  
    System.out.printf("Event %s has happened,which fileName is %s%n",kind.name(), fileName);  
    }  
    if (!key.reset()) {  
    break;  
    } 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: