利用java7提供的工具包实现文件的创建,修改,删除监控服务。
package com.news.feature;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Files;
import java.nio.file.Path;
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;
/**
* @author Trancy
* @since 2015/04/29
* @功能描述 监控文件状态服务
*/
public class WatchFileService {
/**
* @author Trancy
* @throws IOException
* @throws InterruptedException
* @功能描述 監控文件创建
*/
public static void FileWatch(String filepath) throws IOException,
InterruptedException {
WatchService service = FileSystems.getDefault().newWatchService();
Path path = Paths.get(filepath).toAbsolutePath();
path.register(
service, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY,
StandardWatchEventKinds.ENTRY_DELETE);
while (true) {
WatchKey key = service.take();
for (WatchEvent<?> event : key.pollEvents()) {
System.out.println(event.kind().toString());
if (event.kind().equals(StandardWatchEventKinds.ENTRY_CREATE)) {
Path createdPath = (Path) event.context();
createdPath = path.resolve(createdPath);
long size = Files.size(createdPath);
System.out.println("创建文件:" + createdPath + "==>" + size);
} else if (event.kind().equals(StandardWatchEventKinds.ENTRY_MODIFY)) {
Path createdPath = (Path) event.context();
createdPath = path.resolve(createdPath);
long size = Files.size(createdPath);
System.out.println("修改文件:" + createdPath + "==>" + size);
} else if (event.kind().equals(StandardWatchEventKinds.ENTRY_DELETE)) {
Path createdPath = (Path) event.context();
createdPath = path.resolve(createdPath);
System.out.println("删除 文件:" + createdPath);
}
}
key.reset();
}
}
public static void main(String[] args) {
try {
FileWatch("D:/资料/MOBI");
} catch (IOException e) {
e.printStackTrace();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}