| 代码如下 | 复制代码 |
packageservice;
importconfig.Config; importjava.io.IOException; importjava.nio.file.*; importjava.util.List; importjava.util.concurrent.TimeUnit;
publicclassWatchDirService { privateWatchService watchService; privatebooleannotDone =true;
publicWatchDirService(String dirPath){ init(dirPath); }
privatevoidinit(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(); } }
publicvoidstart(){ System.out.print("watch..."); while(notDone){ try{ WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS);//此处将处于等待状态,等待检测到文件夹下得文件发生改变,返回WatchKey对象 if(watchKey !=null){ List for(WatchEvent event : events){ WatchEvent.Kind> kind = event.kind(); if(kind == StandardWatchEventKinds.OVERFLOW){ //当前磁盘不可用 continue; } WatchEvent Path path = ev.context(); if(kind == StandardWatchEventKinds.ENTRY_CREATE){ System.out.println("create "+ path.getFileName()); }elseif(kind == StandardWatchEventKinds.ENTRY_MODIFY){ System.out.println("modify "+ path.getFileName()); }elseif(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; } } } } | |
就是这么简单就可以对一个文件夹进行监控了。
摩托车销售模拟器内置菜单中文版
摩托车出售模拟器,又名摩托车销售模拟器,这是一个以摩托车销售
船舶模拟2020最新版
船舶模拟2020是玩法非常有意思的模拟驾驶游戏,高清3d画质
油管主播的生活2内置菜单版
油管主播的生活2内置菜单版是一款模拟养成类游戏,在这里你将体
网吧老板模拟器2手机版
网吧老板模拟器2是非常受欢迎的模拟经营题材手游,在原本的基础
美国警察模拟器巡警2024最新版
美国警察模拟器是一款好玩的模拟手游,游戏中你将扮演一位警察,