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();
}
}
}
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();
}
}
}