功能

实现当文件内容发生变化时,重新加载文件,可用于读取配置类的文件。

原理

注册一个listener,然后新开个线程,定期去扫描文件,通过对文件内容进行hash来判断文件内容是否发生变化,如果变化了,则回调监听器的onChange方法。

实现

实现来源于RocketMQ源码,经过一定的删减。若需要阅读更完整的代码,请至RocketMQ官网下载完整源码。

public class FileWatchService implements Runnable {

    private final List<String> watchFiles;
    private final List<String> fileCurrentHash;
    private final Listener listener;
    private static final int WATCH_INTERVAL = 500;
    private MessageDigest md = MessageDigest.getInstance("MD5");
    private volatile boolean stopped = false;

    public FileWatchService(final String[] watchFiles,
                            final Listener listener) throws Exception {
        this.listener = listener;
        this.watchFiles = new ArrayList<>();
        this.fileCurrentHash = new ArrayList<>();

        for (int i = 0; i < watchFiles.length; i++) {
            if (null != watchFiles[i] && watchFiles[i].trim().length() >0 && new File(watchFiles[i]).exists()) {
                this.watchFiles.add(watchFiles[i]);
                this.fileCurrentHash.add(hash(watchFiles[i]));
            }
        }
    }

    public String getServiceName() {
        return "FileWatchService";
    }

    @Override
    public void run() {
        System.out.println(this.getServiceName() + " service started");
        while (!this.isStopped()) {
            try {
                Thread.sleep(WATCH_INTERVAL);

                for (int i = 0; i < watchFiles.size(); i++) {
                    String newHash;
                    try {
                        newHash = hash(watchFiles.get(i));
                    } catch (Exception ignored) {
                        ignored.printStackTrace();
                        continue;
                    }
                    if (!newHash.equals(fileCurrentHash.get(i))) {
                        fileCurrentHash.set(i, newHash);
                        listener.onChanged(watchFiles.get(i));
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }

    private String hash(String filePath) throws IOException, NoSuchAlgorithmException {
        Path path = Paths.get(filePath);
        md.update(Files.readAllBytes(path));
        byte[] hash = md.digest();
        return UtilAll.bytes2string(hash);
    }


    public boolean isStopped() {
        return stopped;
    }

    public void start() {
        Thread thread = new Thread(this);
        thread.start();
    }

    public interface Listener {
        /**
         * Will be called when the target files are changed
         * @param path the changed file path
         */
        void onChanged(String path);
    }
}
public class UtilAll {

    final static char[] HEX_ARRAY = "0123456789ABCDEF".toCharArray();

    public static String bytes2string(byte[] src) {
        char[] hexChars = new char[src.length * 2];
        for (int j = 0; j < src.length; j++) {
            int v = src[j] & 0xFF;
            hexChars[j * 2] = HEX_ARRAY[v >>> 4];
            hexChars[j * 2 + 1] = HEX_ARRAY[v & 0x0F];
        }
        return new String(hexChars);
    }
}
public class FileChangeMain {
    public static void main(String[] args) {
        try {
            FileWatchService fileWatchService = new FileWatchService(
                    new String[] {
                            "test.txt"
                    },
                    new FileWatchService.Listener() {
                        @Override
                        public void onChanged(String path) {
                            System.out.println("文件" + path + "发生变化了,重新加载");
                            reload();
                        }
                        private void reload() {
                            System.out.println("重新加载文件");
                        }
                    });
            fileWatchService.start();
        } catch (Exception e){
            e.printStackTrace();
        }

    }
}

运行效果

文件监听器运行结果.PNG


bugDesigner
22 声望3 粉丝