监听文件修改

public class WatchFile {

private static final Logger logger = LoggerFactory.getLogger(WatchFile.class);

private ExecutorService executorService = Executors.newSingleThreadExecutor();

private WatchService watchService;

private ConcurrentHashMap> listen = new ConcurrentHashMap<>();

private static WatchFile watchFile;

public static WatchFile getWatchFile() {
    if (watchFile == null) {
        synchronized (watchFile) {
            if (watchFile == null) {
                try {
                    watchFile.watchService = FileSystems.getDefault().newWatchService();
                    watchFile.executorService.execute(new Task());
                } catch (IOException e) {
                    logger.error("WatchFile初始化错误" );
                    e.printStackTrace();
                }
            }
        }
    }
    return watchFile;
}

public void register(String fileName, Callback object) {
    try {
        Paths.get(fileName).register(watchService, StandardWatchEventKinds.ENTRY_MODIFY);
        List list = listen.get(fileName);
        if(list == null)
           list = new ArrayList()
        list.add(object);
        listen.put(fileName, list);
    } catch (IOException e) {
        logger.error("加入监听失败", fileName);
        e.printStackTrace();
    }
}

static class Task implements Runnable {



    @Override
    public void run() {
        while (true) {
            WatchKey watchKey = null;
            try {
                watchKey = watchFile.watchService.take();
                watchKey.pollEvents().stream().forEach(event -> {
                    WatchEvent e = (WatchEvent) event;
                    Path path = e.context();
                    String fileName = path.toFile().getName();
                    List list = watchFile.listen.get(fileName);
                    for(CallBack callback :list){
                         callback.callback();
                    }
                });

            } catch (Exception e) {
                logger.error(e.getMessage(), e);
            } finally {
                watchKey.reset();
            }
        }

    }
}

你可能感兴趣的:(监听文件修改)