The Fourth Dimension Space

枯叶北风寒,忽然年以残,念往昔,语默心酸。二十光阴无一物,韶光贱,寐难安; 不畏形影单,道途阻且慢,哪曲折,如渡飞湍。斩浪劈波酬壮志,同把酒,共言欢! -如梦令

JAVA File Watcher Service

public static void main(String[] args) throws IOException
    {
        try
        {
            WatchService watcher = FileSystems.getDefault().newWatchService();
            Path watchedDir = Paths.get("C:\\Users\\Administrator\\workspace\\test");
            WatchKey key = watchedDir.register(watcher, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,StandardWatchEventKinds.ENTRY_MODIFY);
            System.out.println("Watching "+ watchedDir);
        
            while(true)
            {
                key = watcher.take(); 
                for(WatchEvent<?> event: key.pollEvents())
                {
                    WatchEvent.Kind<?> kind = event.kind();
                    WatchEvent<Path> ev = (WatchEvent<Path>)event;
                    Path pathName = ev.context();
                    if(kind == StandardWatchEventKinds.ENTRY_MODIFY)
                        System.out.println(pathName + " modified!");
                    else if(kind == StandardWatchEventKinds.ENTRY_DELETE)
                        System.out.println(pathName+" deleted");
                    else {
                        System.out.println(pathName + "created");
                    }
                }
                key.reset();
            }
            
        } catch (InterruptedException e) {
            // TODO 自动生成的 catch 块
            e.printStackTrace();
        }
    }

输出:
Watching C:\Users\Administrator\workspace\test
test7.txt deleted
test8.txtcreated
test8.txt modified!
newFilecreated
newFile modified!
newFile modified!
newDircreated
newDir modified!
.newFile.swpcreated
.newFile.swp modified!
.newFile.swpxcreated
.newFile.swpx modified!
.newFile.swpx deleted
.newFile.swp deleted
.newFile.swpcreated
.newFile.swp modified!
.newFile.swp modified!
.newFile.swp modified!
newFile~created
newFile~ modified!
newFile~ modified!
newFile~ modified!
newFile~ modified!
newFile~ modified!
newFile modified!
newFile modified!
newFile~ deleted
.newFile.swp modified!
.newFile.swp deleted
newDir deleted
newFile deleted
test8.txt deleted
新建文件夹 deleted

posted on 2014-09-17 22:36 abilitytao 阅读(538) 评论(0)  编辑 收藏 引用


只有注册用户登录后才能发表评论。
【推荐】超50万行VC++源码: 大型组态工控、电力仿真CAD与GIS源码库
网站导航: 博客园   IT新闻   BlogJava   知识库   博问   管理