通過java7提供的WatchService API 實現(xiàn)對文件夾的監(jiān)控
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
56
57
58
59
60
61
62
63
64
65
|
package service; import config.Config; import java.io.IOException; import java.nio.file.*; import java.util.List; import java.util.concurrent.TimeUnit; public class WatchDirService { private WatchService watchService; private boolean notDone = true ; public WatchDirService(String dirPath){ init(dirPath); } private void init(String dirPath) { Path path = Paths.get(dirPath); try { watchService = FileSystems.getDefault().newWatchService(); //創(chuàng)建watchService path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE); //注冊需要監(jiān)控的事件,ENTRY_CREATE 文件創(chuàng)建,ENTRY_MODIFY 文件修改,ENTRY_MODIFY 文件刪除 } catch (IOException e) { e.printStackTrace(); } } public void start(){ System.out.print( "watch..." ); while (notDone){ try { WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS); //此處將處于等待狀態(tài),等待檢測到文件夾下得文件發(fā)生改變,返回WatchKey對象 if (watchKey != null ){ List<WatchEvent<?>> events = watchKey.pollEvents(); //獲取所有得事件 for (WatchEvent event : events){ WatchEvent.Kind<?> kind = event.kind(); if (kind == StandardWatchEventKinds.OVERFLOW){ //當(dāng)前磁盤不可用 continue ; } WatchEvent<Path> ev = event; Path path = ev.context(); if (kind == StandardWatchEventKinds.ENTRY_CREATE){ System.out.println( "create " + path.getFileName()); } else if (kind == StandardWatchEventKinds.ENTRY_MODIFY){ System.out.println( "modify " + path.getFileName()); } else if (kind == StandardWatchEventKinds.ENTRY_DELETE){ System.out.println( "delete " + path.getFileName()); } } if (!watchKey.reset()){ //已經(jīng)關(guān)閉了進(jìn)程 System.out.println( "exit watch server" ); break ; } } } catch (InterruptedException e) { e.printStackTrace(); return ; } } } } |
就是這么簡單就可以對一個文件夾進(jìn)行監(jiān)控了。
完整帶碼地址:WatchServerDemo.rar
以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。
原文鏈接:http://www.jianshu.com/p/928ce1010407