Java实现文件夹的监控
一、实现单级文件夹的监听(只监听该文件夹下的变化)
public static void main(String[] args) {
final Path path = Paths.get("D:\\test");
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
//给path路径加上文件观察服务
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE);
while (true) {
final WatchKey key = watchService.take();
for (WatchEvent<?> watchEvent : key.pollEvents()) {
final WatchEvent.Kind<?> kind = watchEvent.kind();
if (kind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
//创建事件
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("[新建]");
}
//修改事件
if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("修改]");
}
//删除事件
if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("[删除]");
}
// get the filename for the event
final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;
final Path filename = watchEventPath.context();
// print it out
System.out.println(kind + " -> " + filename);
}
boolean valid = key.reset();
if (!valid) {
break;
}
}
} catch (IOException | InterruptedException ex) {
System.err.println(ex);
}
}
自定义监听模式:
public static boolean watchDirectory(String dirPath) {
// 判断要监控的目录是否存在
if (!(new File(dirPath).exists())) {
System.out.println(MessageFormat.format("目录{0}不存在!", dirPath));
return false;
}
// 注册要监控的文件夹
Path watchDirectory = Paths.get(new File(dirPath).getPath());
try (WatchService watchService = FileSystems.getDefault().newWatchService()) {
watchDirectory.register(watchService,
// 指定要监控的文件操作类型,创建/修改/删除
StandardWatchEventKinds.ENTRY_CREATE);
// watchDirectory.register(watchService,StandardWatchEventKinds.ENTRY_MODIFY);
// watchDirectory.register(watchService,StandardWatchEventKinds.ENTRY_DELETE);
// 死循环执行监控
while (true) {
// 获取文件操作对象
WatchKey watchKey = watchService.take();
// 针对不同的文件操作类型进行处理
for (WatchEvent event : watchKey.pollEvents()) {
WatchEvent.Kind eventKind = event.kind();
if (eventKind == StandardWatchEventKinds.OVERFLOW) {
continue;
}
// 获取发生改变的文件名
String fileName = event.context().toString();
// 当文件创建执行
if (eventKind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println(fileName);
String path=dirPath+"/"+fileName;
System.out.println(path);
if (new File(path).isDirectory()){
System.out.println("文件夹");
}else {
System.out.println("文件");
}
}
}
// 每次执行完后重置
boolean isKeyValid = watchKey.reset();
if (!isKeyValid) {
break;
}
}
} catch (IOException | InterruptedException e) {
e.printStackTrace();
}
return true;
}
二、实现多级文件夹的监听(监听该文件夹及以下文件及文件夹的变化)
public class FileListener extends FileAlterationListenerAdaptor {
private Logger log = Logger.getLogger(FileListener.class);
/**
* 文件创建执行
*/
public void onFileCreate(File file) {
log.info("[新建]:" + file.getAbsolutePath());
}
/**
* 文件创建修改
*/
public void onFileChange(File file) {
log.info("[修改]:" + file.getAbsolutePath());
}
/**
* 文件删除
*/
public void onFileDelete(File file) {
log.info("[删除]:" + file.getAbsolutePath());
}
/**
* 目录创建
*/
public void onDirectoryCreate(File directory) {
log.info("[新建]:" + directory.getAbsolutePath());
}
/**
* 目录修改
*/
public void onDirectoryChange(File directory) {
log.info("[修改]:" + directory.getAbsolutePath());
}
/**
* 目录删除
*/
public void onDirectoryDelete(File directory) {
log.info("[删除]:" + directory.getAbsolutePath());
}
public void onStart(FileAlterationObserver observer) {
// TODO Auto-generated method stub
super.onStart(observer);
}
public void onStop(FileAlterationObserver observer) {
// TODO Auto-generated method stub
super.onStop(observer);
}
}
public static void main(String[] args) {
// 轮询间隔 5 秒
long interval = TimeUnit.SECONDS.toMillis(5);
//不使用过滤器,使用过滤器时创建FileAlterationObserver对象时传入第二个参数FileFilter
FileAlterationObserver observer = new FileAlterationObserver(new File("D:\\test"));
FileListener fileListener = new FileListener();
observer.addListener(fileListener);
//创建文件变化监听器
FileAlterationMonitor monitor = new FileAlterationMonitor(interval, observer);
// 开始监控
try {
monitor.start();
}catch (Exception e){}
}
版权声明:本文为m0_50008952原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。