监听文件变化

目录
  1. 使用场景
  2. 例子
  3. 注意
使用场景

对于某些文件的变化进行监听操作(如IDE及各编辑器监听文件变化来进行同步,应用服务器监听如jsp、jar等文件的变化来重新部署)。
个人学习使用该API的目的是想监听功能开关配置文件,达到修改文件后,程序重新加载配置到内存的目的。

例子
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
import java.nio.file.FileSystems;
import java.nio.file.Files;
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;

public class PathsDemo {
public static void main(String[] args){
try {
//The first step is to create a new WatchService by using the newWatchService method in the FileSystem class.
WatchService watchService=FileSystems.getDefault().newWatchService();

//register one or more objects with the watch service.
//When registering an object with the watch service, you specify the types of events that you want to monitor.
Paths.get(propertiesPath).register(watchService,
StandardWatchEventKinds.ENTRY_CREATE, //A directory entry is created
StandardWatchEventKinds.ENTRY_DELETE, //A directory entry is deleted
StandardWatchEventKinds.ENTRY_MODIFY);//A directory entry is modified.

while(true)
{
//Returns a queued key. If no queued key is available, this method waits.
WatchKey key=watchService.take();
for(WatchEvent<?> event:key.pollEvents())
{
System.out.println(event.context()+" happens "+event.kind()+" event.");
//TODO business operations...
}
if(!key.reset())
{
break;
}
}
} catch (Exception e) {
System.err.println(e);
}
}
}
1
2
//控制台输出
config.properties happen ENTRY_MODIFY event.
注意

Java7 才支持NIO Paths。
该API 设计不是用于索引硬盘。