集册 Java实例教程 监视路径的创建、删除和修改事件,并报告事件类型和发生事件的文件

监视路径的创建、删除和修改事件,并报告事件类型和发生事件的文件

欢马劈雪     最近更新时间:2020-01-02 10:19:05

345
监视路径的创建,删除和修改事件,并报告事件的类型和发生事件的文件
//时代Java - N o w  J a v a . c o m 提 供

import java.io.IOException;

import java.nio.file.FileSystems;

import java.nio.file.Path;

import java.nio.file.Paths;

import java.nio.file.StandardWatchEventKinds;

import java.nio.file.WatchEvent;

import java.nio.file.WatchEvent.Kind;

import java.nio.file.WatchKey;

import java.nio.file.WatchService;

public class Main {

  public static void main(String[] args)  throws Exception{

    Path path = Paths.get("C:/folder1");

    try (WatchService watchService = FileSystems.getDefault().newWatchService()) {

      path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,

          StandardWatchEventKinds.ENTRY_MODIFY,

          StandardWatchEventKinds.ENTRY_DELETE);

      while (true) {

        final WatchKey key = watchService.take();
        /*
        时 代 J a v a 公 众 号 - N o w J a v  a . c o m 提 供
        */

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

          final Kind<?> kind = watchEvent.kind();

          if (kind == StandardWatchEventKinds.OVERFLOW) {

            continue;

          }

          final WatchEvent<Path> watchEventPath = (WatchEvent<Path>) watchEvent;

          final Path filename = wa
展开阅读全文