文件变化监视 java.nio.file.WatchService

WatchKey java.nio.file.Path. register(WatchService watcher, Kind<?>... events) throws IOException
为该文件注册watch service。
Registers the file located by this path with a watch service. 

WatchKey java.nio.file.WatchService. take() throws InterruptedException
检索并移除下一个watch key。若没有可检索的则阻塞。
Retrieves and removes next watch key, waiting if none are yet present.

List<WatchEvent<?>> java.nio.file.WatchKey. pollEvents()
检索并移除所有该watch key
Retrieves and removes all pending events for this watch key, returning a List of the events that were retrieved. 

Kind<?> java.nio.file.WatchEvent. kind()
返回事件种类
Returns the event kind.

String java.nio.file.WatchEvent.Kind. name()
返回事件种类的名字。
Returns the name of the event kind.

? java.nio.file.WatchEvent. context()
返回事件发生的环境,简单讲就是不带路径的文件名。
Returns the context for the event. 

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.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

import static java.nio.file.StandardWatchEventKinds.*;

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()){
                Kind
   
    kind = event.kind();
                
                if(kind == OVERFLOW){//事件可能lost or discarded
                    continue;
                }
                Path fileName = (Path) event.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{
        new TestWatcherService(Paths.get("c:\\t\\")).handleEvents();
    }
}
/*
 * Event ENTRY_MODIFY has happened,which fileName is 新建文本文档.txt
Event ENTRY_CREATE has happened,which fileName is 新建文件夹 (2)
Event ENTRY_DELETE has happened,which fileName is 新建文本文档 (2).txt
Event ENTRY_CREATE has happened,which fileName is 新建文本搜索文档 (2).txt
Event ENTRY_MODIFY has happened,which fileName is 新建文本搜索文档 (2).txt
*/
/*更名会被认为是删除->新建->修改内容*/
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值