WatchFile监听目录下文件的改动

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/xingxiupaioxue/article/details/82901403

public static void fileListener(String filePath) throws InterruptedException,IOException{
         // 获取文件系统的WatchService对象
        WatchService watchService = FileSystems.getDefault().newWatchService();
        String parentPath = filePath.substring(0,filePath.lastIndexOf(File.separator));
        Paths.get(parentPath).register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_DELETE);  
        
        while(true)
        {
            // 获取下一个文件改动事件
            WatchKey key = watchService.take();
            for (WatchEvent<?> event : key.pollEvents()) 
            {
                System.out.println(event.context() +" --> " + event.kind());
                File file = new File(filePath);
                if(!file.exists()){
                    log.error(filePath+"cnr配置文件不存在");
                    break;
                }
                String ms= IOUtils.readFile(filePath);
                
               
                paramSetService.addParamSet(ms);
            }
            // 重设WatchKey
            boolean valid = key.reset();
            // 如果重设失败,退出监听
            if (!valid) 
            {
                break;
            }
        }
    }

猜你喜欢

转载自blog.csdn.net/xingxiupaioxue/article/details/82901403
今日推荐