java7 NIO2(6) watching service API
来源:互联网 发布:千牛mac官方下载 编辑:程序博客网 时间:2024/06/04 18:59
java7 NIO2新增了文件系统的相关事件处理API,为目录,文件新增修改删除等事件添加事件处理。
package com.mime;import java.io.IOException;import java.nio.file.FileSystems;import java.nio.file.Path;import java.nio.file.Paths;import java.nio.file.StandardWatchEventKinds;import java.nio.file.WatchEvent;import java.nio.file.WatchEvent.Kind;import java.nio.file.WatchKey;import java.nio.file.WatchService;public class NIO2WatchService {//WatchService 是线程安全的,跟踪文件事件的服务,一般是用独立线程启动跟踪public void watchRNDir(Path path) throws IOException, InterruptedException {try (WatchService watchService = FileSystems.getDefault().newWatchService()) {//给path路径加上文件观察服务path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_DELETE);// start an infinite loopwhile (true) {// retrieve and remove the next watch keyfinal WatchKey key = watchService.take();// get list of pending events for the watch keyfor (WatchEvent<?> watchEvent : key.pollEvents()) {// get the kind of event (create, modify, delete)final Kind<?> kind = watchEvent.kind();// handle OVERFLOW eventif (kind == StandardWatchEventKinds.OVERFLOW) {continue;}//创建事件if(kind == StandardWatchEventKinds.ENTRY_CREATE){}//修改事件if(kind == StandardWatchEventKinds.ENTRY_MODIFY){}//删除事件if(kind == StandardWatchEventKinds.ENTRY_DELETE){}// get the filename for the eventfinal WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;final Path filename = watchEventPath.context();// print it outSystem.out.println(kind + " -> " + filename);}// reset the keyfboolean valid = key.reset();// exit loop if the key is not valid (if the directory was// deleted, forif (!valid) {break;}}}}/** * @param args */public static void main(String[] args) {final Path path = Paths.get("/tmp");NIO2WatchService watch = new NIO2WatchService();try {watch.watchRNDir(path);} catch (IOException | InterruptedException ex) {System.err.println(ex);}}}
- java7 NIO2(6) watching service API
- java7 NIO2(7) random access file API
- Java7 NIO2
- java7 NIO2(8)The Asynchronous Channel API 异步通道API
- java7 NIO2(4) 文件和目录操作API
- java7 NIO2(5) 文件和目录操作API
- Java7 NIO2 Path类
- Java7 nio2 异步Socket实践
- java7 NIO2(3) 文件链接操作
- nio2
- nio2
- NIO2浅入浅出之异步通道 API
- JAVA7 新增工具api
- java7.6
- java 7 NIO2(1) Path类相关新API
- java7
- Java7
- Java7
- Unity动画事件
- 如何利用JM8.6解码器提取码流中P帧宏块(所有4*4块)的运动矢量(考虑B帧,设x264编码的12帧为IDR BBPBBPBBPBP)
- 基础文章7:chap15 进程通信之管道 补充
- STL algorithm之copy
- RPG游戏中阻碍半透明遮挡(C# XNA)
- java7 NIO2(6) watching service API
- 开源 免费 java CMS - FreeCMS-标签 infoList
- 磁盘分区
- Android Bundle类
- Python类
- rman 迁移ASM到异机文件系统实战
- Apache configuration files on Ubuntu
- Linux 常用命令——chgrp, chown, chmod
- 别问我了,我告诉你如何记住解压命令