Java监控文件变化
2012-08-22 20:28
417 查看
NIO.2的Path类提供了如下的一个方法来监听文件系统的变化。
register(WatcherService watcher,WatchEvent.Kind<?>... events):用watcher监听该path代表的目录下文件变化。event参数指定要监听哪些类型的事件。
WatchService有三个方法来监听目录的文件变化事件。
WatchKey poll():获取下一个WatchKey,如果没有WatchKey发生就立即返回null;
WatcheKey poll(long timeout,TimeUnit unit):尝试等待timeout时间去获取下一个WatchKey;
WatchKey take():获取下一个WatchKey,如果没有发生就一直等待;
如果程序需要一直监控,则应该选择使用take()方法,如果程序只需要监控指定时间,则使用poll方法。
register(WatcherService watcher,WatchEvent.Kind<?>... events):用watcher监听该path代表的目录下文件变化。event参数指定要监听哪些类型的事件。
WatchService有三个方法来监听目录的文件变化事件。
WatchKey poll():获取下一个WatchKey,如果没有WatchKey发生就立即返回null;
WatcheKey poll(long timeout,TimeUnit unit):尝试等待timeout时间去获取下一个WatchKey;
WatchKey take():获取下一个WatchKey,如果没有发生就一直等待;
如果程序需要一直监控,则应该选择使用take()方法,如果程序只需要监控指定时间,则使用poll方法。
import java.nio.file.FileSystems; import java.nio.file.Paths; import java.nio.file.StandardWatchEventKinds; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchService; public class Test { public static void main(String[] args) throws Exception { WatchService watchService=FileSystems.getDefault().newWatchService(); Paths.get("C:/").register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY); while(true) { WatchKey key=watchService.take(); for(WatchEvent<?> event:key.pollEvents()) { System.out.println(event.context()+"发生了"+event.kind()+"事件"); } if(!key.reset()) { break; } } } }
相关文章推荐
- 使用apache common-io 定时监控文件下文件的变化,java文件扫描文件变化
- java 使用线程监控文件目录变化的实现方法
- Java监控文件变化
- java实现文件变化监控
- Java实现文件变化监控
- java读取系统Properties配置文件利用线程实时监控配置文件变化
- java 使用线程监控文件目录变化的实现方法
- Java中监控文件变化的多种方案
- java监控文件夹内文件变化并且进行文件同步bigfilesync
- java实现文件变化监控
- [疯狂Java]NIO.2:WatchService、WatchKey(监控文件变化)
- java 实现监控某目录文件变化
- JAVA实时监控目录下文件的变化
- java监控指定路径下文件及文件夹变化
- Java使用WatchService监控文件内容变化的示例
- java实现文件变化监控的方法(推荐)
- Java实现监控目录下文件变化
- java 监控文件夹变化(钩子文件)
- java读取系统Properties配置文件利用线程实时监控配置文件变化
- Java 如何监控文件目录的变化 【转】