文件变化监视 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> 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
*/
/*更名会被认为是删除->新建->修改内容*/

你可能感兴趣的:(数据读写(I/O))