您的位置:首页 > 编程语言 > Java开发

Java7 WatchService 监控文件变化

2015-04-20 23:38 423 查看
package com.test.watchservice;

import java.io.IOException;

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 TestWatchService {

public static void main(String[] args) {

//获取文件系统的WatchService 对象

try {

WatchService watchService = FileSystems.getDefault().newWatchService();

//为指定目录路径注册舰艇

Paths.get("E:\\").register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_DELETE);

while(true){

//获取下一个文件变化事件

try {

WatchKey key = watchService.take();

for (WatchEvent<?> enent : key.pollEvents()) {

System.out.println(enent.context()+"文件发生了"+enent.kind()+"事件");

}

} catch (InterruptedException e) {

e.printStackTrace();

}

}

} catch (IOException e) {

e.printStackTrace();

}

}

}
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: