2018년 3월 21일 수요일

[Java] WatchService Examples to get file and directory change event in Java


1. Get File/Directory change event with WatchService example

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
import java.io.File;
import java.io.IOException;
import java.nio.file.FileSystems;
import java.nio.file.Path;
import java.nio.file.StandardWatchEventKinds;
import java.nio.file.WatchEvent;
import java.nio.file.WatchEvent.Kind;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.Arrays;

public class Watcher {

    WatchService watcher;
    WatchKey watchKey;
    String folder;
            
    Watcher(String folder) throws IOException {
        this.folder = folder;
        this.watcher = FileSystems.getDefault().newWatchService();
        java.nio.file.Paths.get(folder).register(watcher, StandardWatchEventKinds.ENTRY_CREATE);
    }

    Watcher(String folder, boolean create, boolean delete, boolean modity) throws IOException {
        this.folder = folder;
        this.watcher = FileSystems.getDefault().newWatchService();
        int i = 0;
        Kind[] kinds = new Kind[3];
        if( create ) { kinds[i++] = StandardWatchEventKinds.ENTRY_CREATE; }
        if( delete ) { kinds[i++] = StandardWatchEventKinds.ENTRY_DELETE; }
        if( modity ) { kinds[i++] = StandardWatchEventKinds.ENTRY_MODIFY; }
        java.nio.file.Paths.get(folder).register(watcher, Arrays.copyOf(kinds,i));
    }

    public void loop() {
        while( true ) {
            try {
                watchKey = watcher.take();
                for (final WatchEvent event : watchKey.pollEvents()) {
                    final WatchEvent.Kind kind = event.kind();
                    final Path changed = (Path) event.context();
                    File f = new File( folder, changed.toFile().getPath() );
                    System.out.println(f.getPath() + ":" + kind);
                }
                boolean valid = watchKey.reset();
                if( !valid ) {
                    System.out.println("Watch Key has been reset...");
                }
            } catch (InterruptedException e) {
            }
        }
    }    
    
    public static void main(String[] args) {
        try {
            Watcher w = new Watcher("D:/Temp",true,true,true);
            w.loop();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}


Result:
D:\Temp\jsch-0.1.54.zip:ENTRY_CREATE
D:\Temp\jsch-0.1.54.zip:ENTRY_MODIFY
D:\Temp\jsch-0.1.54.zip:ENTRY_MODIFY
D:\Temp\one-ftpserver-master.zip:ENTRY_CREATE
D:\Temp\one-ftpserver-master.zip:ENTRY_MODIFY
D:\Temp\jsch-0.1.54.zip:ENTRY_DELETE
D:\Temp\one-ftpserver-master.zip:ENTRY_DELETE




댓글 없음:

댓글 쓰기