首页 诗词 字典 板报 句子 名言 友答 励志 学校 网站地图
当前位置: 首页 > 教程频道 > 开发语言 > 编程 >

NIO2.0资料监听

2012-12-23 
NIO2.0文件监听import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATEimport static java.n

NIO2.0文件监听
import static java.nio.file.StandardWatchEventKinds.ENTRY_CREATE;
import static java.nio.file.StandardWatchEventKinds.OVERFLOW;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;

/*
* 文件监听
*
* 实现流程如下:
*
*1.为文件系统创建一个WatchService 实例 watcher
*2.为你想监听的目录注册 watcher。注册时,要注明监听那些事件。
*3.在无限循环里面等待事件的触发。当一个事件发生时,key发出信号,并且加入到watcher的queue
*4.从watcher的queue查找到key,你可以从中获取到文件名等相关信息
*5.遍历key的各种事件
*6.重置 key,重新等待事件
*7.关闭服务
*/
public class TestIOWatchDir {
public void watchDir(String dirPath) {
try {
Path path = Paths.get(dirPath);
WatchService watcher = FileSystems.getDefault().newWatchService();
//path.register(watcher, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY);
path.register(watcher, ENTRY_CREATE);
while (true) {
WatchKey key = watcher.take();
for (WatchEvent<?> event : key.pollEvents()) {
WatchEvent.Kind<?> kind = event.kind();
if (kind == OVERFLOW) {
continue;
}
Path filePath = (Path) event.context();
System.out.println(filePath);
key.reset();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}

public static void main(String[] args) {
String dirPath = "D:/";
new TestIOWatchDir().watchDir(dirPath);
}

}

备注:参考的相关资源来源于网络ITEYE

热点排行