1 import config.Config;
2
3 import java.io.IOException;
4 import java.nio.file.*;
5 import java.util.List;
6 import java.util.concurrent.TimeUnit;
7
8 /**
9 * Created by jason on 2017/2/14.
10 */
11 public class WatchDirService {
12 private WatchService watchService;
13 private boolean notDone = true;
14
15 public WatchDirService(String dirPath){
16 init(dirPath);
17 }
18
19 private void init(String dirPath) {
20 Path path = Paths.get(dirPath);
21 try {
22 watchService = FileSystems.getDefault().newWatchService();
23 path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,StandardWatchEventKinds.ENTRY_MODIFY,StandardWatchEventKinds.ENTRY_DELETE);
24 } catch (IOException e) {
25 e.printStackTrace();
26 }
27 }
28
29 public void start(){
30 System.out.print("watch...");
31 while (notDone){
32 try {
33 WatchKey watchKey = watchService.poll(Config.POLL_TIME_OUT, TimeUnit.SECONDS);
34 System.out.print("change");
35 if(watchKey != null){
36 List<WatchEvent<?>> events = watchKey.pollEvents();
37 for (WatchEvent event : events){
38 WatchEvent.Kind<?> kind = event.kind();
39 if (kind == StandardWatchEventKinds.OVERFLOW){
40 continue;
41 }
42 WatchEvent<Path> ev = event;
43 Path path = ev.context();
44 if(kind == StandardWatchEventKinds.ENTRY_CREATE){
45 System.out.println("create " + path.getFileName());
46 }else if(kind == StandardWatchEventKinds.ENTRY_MODIFY){
47 System.out.println("modify " + path.getFileName());
48 }else if(kind == StandardWatchEventKinds.ENTRY_DELETE){
49 System.out.println("delete " + path.getFileName());
50 }
51 }
52 if(!watchKey.reset()){
53 System.out.println("exit watch server");
54 break;
55 }
56 }
57 } catch (InterruptedException e) {
58 e.printStackTrace();
59 return;
60 }
61 }
62 }
63 }