lyh
3 天以前 3ce27b7faf8850d101a1511a685250fe562dca18
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.lxzn.backpass;
 
import org.apache.commons.io.monitor.FileAlterationMonitor;
import org.apache.commons.io.monitor.FileAlterationObserver;
import org.springframework.beans.factory.annotation.Value;
 
import java.io.File;
 
/**
 * @author clown
 * * @date 2023/5/25
 */
public class FileMonitor {
    private FileListener fileListener;  //监听事件
    @Value("${fileNCPath}")
    private String path ;    //监听的文件路径
    private FileAlterationMonitor monitor;
    private long defaultInterval = 10000L;  //默认监听的时间间隔
 
    public FileMonitor(String path) {
        this.path = path;
        this.monitor = new FileAlterationMonitor(defaultInterval);
    }
 
    public FileMonitor() {
        this.monitor = new FileAlterationMonitor(defaultInterval);
    }
 
    public FileMonitor(String path, long interval) {
        this.path = path;
        this.monitor = new FileAlterationMonitor(interval);
    }
 
    public void setFileListener(FileListener fileListener) {
        this.fileListener = fileListener;
    }
 
    public void start() {
        if (monitor == null) {
            throw new IllegalStateException("Listener must not be null");
        }
        if (path == null) {
            throw new IllegalStateException("Listen path must not be null");
        }
        FileAlterationObserver observer = new FileAlterationObserver(new File(path));
        observer.addListener(fileListener);
        monitor.addObserver(observer);
        try {
            monitor.start();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
 
}