在實現配置中心的多種方案中,有基于JDK7+的WatchService方法,其在單機應用中還是挺有實踐的意義的。
代碼如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
|
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監聽文件變化 * @author yangzhilong * */ public class TestWatchService { public static void main(String[] args) throws IOException { // 需要監聽的文件目錄(只能監聽目錄) 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 根據事件類型采取不同的操作。。。。。。。 System.out.println( "[" +path+ "/" +event.context()+ "]文件發生了[" +event.kind()+ "]事件" ); } watchKey.reset(); } } catch (InterruptedException e) { e.printStackTrace(); } }); thread.setDaemon( false ); thread.start(); // 增加jvm關閉的鉤子來關閉監聽 Runtime.getRuntime().addShutdownHook( new Thread(() -> { try { watchService.close(); } catch (Exception e) { } })); } } |
運行示例結果類似如下:
[d:/test/1.txt]文件發生了[ENTRY_MODIFY]事件
[d:/test/1.txt]文件發生了[ENTRY_DELETE]事件
[d:/test/新建文本文檔.txt]文件發生了[ENTRY_CREATE]事件
[d:/test/新建文本文檔.txt]文件發生了[ENTRY_DELETE]事件
[d:/test/222.txt]文件發生了[ENTRY_CREATE]事件
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持服務器之家。
原文鏈接:http://www.cnblogs.com/yangzhilong/p/7487220.html