功能
實現當文件內容發生變化時,重新加載文件,可用於讀取配置類的文件。
原理
註冊一個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();
}
}
}
運行效果