引自: https://www.cnblogs.com/yangzhilong/p/7487220.html

package com.longge.mytest;

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.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

/**
 * 测试JDK的WatchService监听文件变化
 * @author yangzhilong
 *
 */
public class TestWatchService {
    public static void main(String[] args) throws IOException {
        // 需要监听的文件目录(只能监听目录)
        String path = "d:/test";
        
        WatchService watchService = FileSystems.getDefault().newWatchService();
        Path p = Paths.get(path);
        p.register(watchService, StandardWatchEventKinds.ENTRY_MODIFY,  
                StandardWatchEventKinds.ENTRY_DELETE,  
                StandardWatchEventKinds.ENTRY_CREATE);  
        
        Thread thread = new Thread(() -> {
            try {  
                while(true){  
                    WatchKey watchKey = watchService.take();  
                    List<WatchEvent<?>> watchEvents = watchKey.pollEvents();  
                    for(WatchEvent<?> event : watchEvents){  
                        //TODO 根据事件类型采取不同的操作。。。。。。。  
                        System.out.println("["+path+"/"+event.context()+"]文件发生了["+event.kind()+"]事件");    
                    }  
                    watchKey.reset();  
                }  
            } catch (InterruptedException e) {  
                e.printStackTrace();  
            }
        });
        thread.setDaemon(false);
        thread.start();
        
        // 增加jvm关闭的钩子来关闭监听
        Runtime.getRuntime().addShutdownHook(new Thread(() -> {
            try {
                watchService.close();
            } catch (Exception e) {
            }
        }));
    }
}
方法1

相关文章:

  • 2022-12-23
  • 2022-12-23
  • 2021-09-02
  • 2022-12-23
  • 2022-12-23
  • 2021-10-20
  • 2021-11-28
  • 2021-11-07
猜你喜欢
  • 2022-12-23
  • 2022-02-18
  • 2022-01-20
  • 2021-11-11
  • 2022-12-23
  • 2022-02-05
  • 2022-12-23
相关资源
相似解决方案