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

JDK7新特性 监听文件系统的改动

2013-08-01 
JDK7新特性 监听文件系统的更改import java.io.IOExceptionimport java.nio.file.FileSystemsimport jav

JDK7新特性 监听文件系统的更改
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.WatchKey;import java.nio.file.WatchService;import static java.nio.file.StandardWatchEventKind.*;/** * @author kencs@foxmail.com */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()){ WatchEvent.Kind kind = event.kind(); if(kind == OVERFLOW){//事件可能lost or discarded continue; } WatchEvent<Path> e = (WatchEvent<Path>)event; Path fileName = e.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{ if(args.length!=1){ System.out.println("请设置要监听的文件目录作为参数"); System.exit(-1); } new TestWatcherService(Paths.get(args[0])).handleEvents(); }}

?

?

接下来,见证奇迹的时刻

1.随便新建一个文件夹例如 c:\\test
2.运行程序 java TestWatcherService c:\\test
3.在该文件夹下新建一个文件本件“新建文本文档.txt”
4.将上述文件改名为“abc.txt”
5.打开文件,输入点什么吧,再保存。
6.Over!看看命令行输出的信息吧

?



Event ENTRY_CREATE has happened,which fileName is 新建文本文档.txtEvent ENTRY_DELETE has happened,which fileName is 新建文本文档.txtEvent ENTRY_CREATE has happened,which fileName is abc.txtEvent ENTRY_MODIFY has happened,which fileName is abc.txtEvent ENTRY_MODIFY has happened,which fileName is abc.txt



热点排行