NIO实现对文件夹的实时监控
package nio.watchservice;
import java.nio.file.*;
import java.util.concurrent.TimeUnit;
public class FileWatchService {
public static void main(String[] args) {
String baseDir = "D:\\Workspace\\IDEA_PROJECT\\java11_test\\watch-service";
try {
WatchService watchService = FileSystems.getDefault().newWatchService();
Paths.get(baseDir).register(watchService,
StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.OVERFLOW);
while (true) {
WatchKey key = watchService.poll(2, TimeUnit.SECONDS);
if (key == null) {
continue;
}
for (WatchEvent event : key.pollEvents()) {
WatchEvent.Kind kind = event.kind();
Path path = (Path) (event.context());
Path fullPath = Paths.get(baseDir, path.toString());
if (kind == StandardWatchEventKinds.ENTRY_CREATE) {
System.out.println("Create receving File: " + fullPath.toString());
} else if (kind == StandardWatchEventKinds.ENTRY_DELETE) {
System.out.println("Delete receving File: " + fullPath.toString());
} else if (kind == StandardWatchEventKinds.ENTRY_MODIFY) {
System.out.println("Modefy receving File: " + fullPath.toString());
} else if (kind == StandardWatchEventKinds.OVERFLOW) {
System.out.println("Overflow receving File: " + fullPath.toString());
}
}
key.reset();
}
} catch (Exception e) {
e.printStackTrace();
}
}
}