Java利用WatchService監(jiān)聽文件變化示例
在實現(xiàn)配置中心的多種方案中,有基于JDK7+的WatchService方法,其在單機應(yīng)用中還是挺有實踐的意義的。
代碼如下:
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監(jiān)聽文件變化 * @author yangzhilong * */ public class TestWatchService { public static void main(String[] args) throws IOException { // 需要監(jiān)聽的文件目錄(只能監(jiān)聽目錄) 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 根據(jù)事件類型采取不同的操作。。。。。。。 System.out.println("["+path+"/"+event.context()+"]文件發(fā)生了["+event.kind()+"]事件"); } watchKey.reset(); } } catch (InterruptedException e) { e.printStackTrace(); } }); thread.setDaemon(false); thread.start(); // 增加jvm關(guān)閉的鉤子來關(guān)閉監(jiān)聽 Runtime.getRuntime().addShutdownHook(new Thread(() -> { try { watchService.close(); } catch (Exception e) { } })); } }
運行示例結(jié)果類似如下:
[d:/test/1.txt]文件發(fā)生了[ENTRY_MODIFY]事件
[d:/test/1.txt]文件發(fā)生了[ENTRY_DELETE]事件
[d:/test/新建文本文檔.txt]文件發(fā)生了[ENTRY_CREATE]事件
[d:/test/新建文本文檔.txt]文件發(fā)生了[ENTRY_DELETE]事件
[d:/test/222.txt]文件發(fā)生了[ENTRY_CREATE]事件
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot?MP簡單的分頁查詢測試實現(xiàn)步驟分解
好久沒水后端的東西了,最近在做vue項目寫前端的代碼,所以cloud也停進度了,吃完飯突然記得我沒有在博客里寫分頁的東西,雖然項目中用到了,但是沒有拎出來,這里就拎出來看看2023-04-04java讀取文件內(nèi)容,解析Json格式數(shù)據(jù)方式
這篇文章主要介紹了java讀取文件內(nèi)容,解析Json格式數(shù)據(jù)方式,具有很好的參考價值,希望對大家有所幫助。如有錯誤或未考慮完全的地方,望不吝賜教2021-09-09Java實現(xiàn)讀取SFTP服務(wù)器指定目錄文件的方法
SFTP是一種在安全通道上傳輸文件的協(xié)議,它是基于SSH(Secure Shell)協(xié)議的擴展,用于在客戶端和服務(wù)器之間進行加密的文件傳輸,這篇文章主要介紹了Java實現(xiàn)讀取SFTP服務(wù)器指定目錄文件,感興趣的朋友跟隨小編一起看看吧2023-08-08