Java 中实现文件监控,实时监控文件夹下文件的修改,主要的三种方法:
1. JDK 7 的watch service
2. Apache的Commons-IO,来实现文件的监控功能
3. jnotify: https://sourceforge.net/projects/jnotify/
WatchService:
WatchService是监视服务接口, 在不同系统上有不同的实现类。实现了Watchable接口的对象方可注册监视服务,java.nio.file.Path实现了此接口;
WatchKey表示Watchable对象和WatchService的关联关系,在注册时被创建。注册完成后,WatchKey将被置为'ready'状态直到, 下列三种情况之一发生:
- WatchKey.cancel()被调用
- 被监控的目录不存在或不可访问
- WatchService对象被关闭
当文件改动发生时,WatchKey的状态将会被置为"signaled"然后被放入待处理队列中。WatchService提供了三种从队列中获取WatchKeys的方式: - poll - 返回队列中的一个key。如果没有可用的key,将立即返回null。
- poll(long, TimeUnit) - 如果队列中存在可用的key则将之返回,否则在参数预置的时间内等待可用的key。TimeUnit用来指定前一个参数表示的时间是纳秒、毫秒或是其他的时间单位。
例子:final WatchKey watchKey = watchService.poll(1, TimeUnit.MINUTES);将会等待1分钟 - take - 方法将会等待直到可用的key被返回。
缺点:
1. 无法监控子目录下文件的变化
2. 大文件夹下,超慢
代码:
public class FileWatchServiceTask implements Runnable {
private String rootDir;
public FileWatchServiceTask(String rootDir) {
this.rootDir = rootDir;
}
ExecutorService cachedThreadPool = Executors.newFixedThreadPool(5);
@Override
public void run() {
// 获取当前文件系统的监控对象
try(WatchService service = FileSystems.getDefault().newWatchService()){
//获取文件目录下的Path对象注册到 watchService中, 监听的事件类型,有创建,删除,以及修改
Paths.get(rootDir).register(service, StandardWatchEventKinds.ENTRY_CREATE, StandardWatchEventKinds.ENTRY_DELETE, StandardWatchEventKinds.ENTRY_MODIFY);
while (true) {
//获取可用key.没有可用的就wait
WatchKey key = service.take();
for (WatchEvent<?> event : key.pollEvents()) {
// TODO
log.info(event.context() + "文件:" + event.kind() + "次数: " + event.count());
}
// 重置,这一步很重要,否则当前的key就不再会获取将来发生的事件
boolean valid = key.reset();
// 失效状态,退出监听
if (!valid) {
break;
}
}
} catch (IOException | InterruptedException e) {
log.error("Encountered exception when try to get new WatchService : {}", e.fillInStackTrace());
Thread.currentThread().interrupt();
}
}
}
测试代码:
public class JnotifyTest {
public static void main(String[] args) throws Exception {
String rootDir = "C:\\logs";
new CustomJnotifyAdapter(rootDir).beginWatch();
}
}
Apache的common-io
在Apache的Commons-IO中有关于文件的监控功能的代码. 文件监控的原理如下:
由文件监控类FileAlterationMonitor中的线程不停的扫描文件观察器FileAlterationObserver,
如果有文件的变化,则根据相关的文件比较器,判断文件时新增,还是删除,还是更改。(默认为1000毫秒执行一次扫描)
缺点:
1. 内部实现是遍历的方式,小文件夹的效率还好; 比如用测试60G的目录测试,就很慢了
代码:
@Slf4j
public class FileListener extends FileAlterationListenerAdaptor {
/**
* File system observer started checking event.
*
* @param observer The file system observer (ignored)
*/
@Override
public void onStart(FileAlterationObserver observer) {
super.onStart(observer);
}
/**
* Directory created Event.
*
* @param directory The directory created (ignored)
*/
@Override
public void onDirectoryCreate(File directory) {
log.info("[Deleted Directory] : {}",directory.getAbsolutePath());
}
/**
* Directory changed Event.
*
* @param directory The directory changed (ignored)
*/
@Override
public void onDirectoryChange(File directory) {
log.info("[Changed Directory] : {}",directory.getAbsolutePath());
}
/**
* Directory deleted Event.
*
* @param directory The directory deleted (ignored)
*/
@Override
public void onDirectoryDelete(File directory) {
log.info("[Created Directory] : {}",directory.getAbsolutePath());
}
/**
* File created Event.
*
* @param file The file created (ignored)
*/
@Override
public void onFileCreate(File file) {
log.info("[Created File] : {}",file.getAbsolutePath());
}
/**
* File changed Event.
*
* @param file The file changed (ignored)
*/
@Override
public void onFileChange(File file) {
log.info("[Amended File] : {}",file.getAbsolutePath());
}
/**
* File deleted Event.
*
* @param file The file deleted (ignored)
*/
@Override
public void onFileDelete(File file) {
log.info("[Deleted File] : {}",file.getAbsolutePath());
}
/**
* File system observer finished checking event.
*
* @param observer The file system observer (ignored)
*/
@Override
public void onStop(FileAlterationObserver observer) {
super.onStop(observer);
}
}
测试代码:
public class FileMonitorTest {
public static void main(String[] arugs) throws Exception {
//Monitor Directory
String absolateDir = "C:\\logs";
//Interval time 5 seconds
long intervalTime = TimeUnit.SECONDS.toMillis(5);
//Sample 1: Create a file observer to process file type
/*FileAlterationObserver observer1 = new FileAlterationObserver(
absolateDir,
FileFilterUtils.and(
FileFilterUtils.fileFileFilter(),
FileFilterUtils.suffixFileFilter("*.txt")), //filter file type
null);*/
//Sample 2: Create a file Observer to work with file type, eg: Scan the "log" folder under C, and the new file ending with the suffix ".success"
FileAlterationObserver observer2 = new FileAlterationObserver(absolateDir, FileFilterUtils.and(
FileFilterUtils.fileFileFilter(),FileFilterUtils.suffixFileFilter(".success")));
FileAlterationObserver observer = new FileAlterationObserver(absolateDir);
//Set file change listener
observer.addListener(new FileListener());
//Create file change monitor
FileAlterationMonitor monitor = new FileAlterationMonitor(intervalTime, observer);
//start monitor
monitor.start();
//Thread.sleep(30000);
//monitor.stop();
}
Jnotiy
Jnotiy, 支持动态监控(支持级联监控)文件夹和文件的jar包, 先要从https://sourceforge.net/projects/jnotify/下载相应的jar包,
1. 在linux中,调用linux底层的jnotify服务。
2. 在windows中,需要添加附件的dll文件。
本地测试,需要先解压jnotify jar包,复制jnotify_64bit.dll文件到,在本机的jdk的安装目录下的bin目录下:
代码:
@Slf4j
public class CustomJnotifyAdapter extends JNotifyAdapter {
//关注目录的事件
public static final int MASK = JNotify.FILE_CREATED | JNotify.FILE_DELETED | JNotify.FILE_MODIFIED | JNotify.FILE_RENAMED;
/**
* jnotify动态库 - 32位
*/
public static final String NATIVE_LIBRARIES_32BIT = "/lib/native_libraries/32bits/";
/**
* jnotify动态库 - 64位
*/
public static final String NATIVE_LIBRARIES_64BIT = "/lib/native_libraries/64bits/";
private String rootDir;
public CustomJnotifyAdapter(String rootDir){
this.rootDir = rootDir;
}
/**
* 容器启动时启动监视程序
*/
public void beginWatch() throws JNotifyException, NoSuchFieldException, SecurityException, IllegalArgumentException, IllegalAccessException {
/*log.debug("-----------Jnotify test ---------");
Properties sysProps = System.getProperties();
String osArch = (String) sysProps.get("os.arch");
String osName = (String) sysProps.get("os.name");
String userDir = (String) sysProps.getProperty("user.dir");
log.debug("os.arch: " + osArch);
log.debug("os.name: " + osName);
log.debug("userDir: " + userDir);
log.debug("java.class.path: " + sysProps.get("java.class.path"));*/
// 直接调用Jnotify时, 会发生异常:java.lang.UnsatisfiedLinkError: no jnotify_64bit in java.library.path
// 这是由于Jnotify使用JNI技术来加载dll文件,如果在类路径下没有发现相应的文件,就会抛出此异常。
// 因此可以通过指定程序的启动参数: java -Djava.library.path=/path/to/dll,
// 或者是通过修改JVM运行时的系统变量的方式来指定dll文件的路径,如下:
// 判断系统是32bit还是64bit,决定调用对应的dll文件
/*String jnotifyDir = NATIVE_LIBRARIES_64BIT;
if (!osArch.contains("64")) {
jnotifyDir = NATIVE_LIBRARIES_32BIT;
}
log.debug("jnotifyDir: " + jnotifyDir);
// 获取目录路径
String pathToAdd = userDir + jnotifyDir ;
boolean isAdded = false;
final Field usrPathsField = ClassLoader.class.getDeclaredField("usr_paths");
usrPathsField.setAccessible(true);
final String[] paths = (String[]) usrPathsField.get(null);
log.debug("usr_paths: " + Arrays.toString(paths));
for (String path : paths) {
if (path.equals(pathToAdd)) {
isAdded = true;
break;
}
}
if (!isAdded) {
final String[] newPaths = Arrays.copyOf(paths, paths.length + 1);
newPaths[newPaths.length - 1] = pathToAdd;
usrPathsField.set(null, newPaths);
}
log.debug("java.library.path: " + System.getProperty("java.library.path"));
log.debug("usr_paths: " + Arrays.toString((String[]) usrPathsField.get(null)));
usrPathsField.setAccessible(false);
log.debug("类路径加载完成");
*/
//是否监视子目录,即级联监视
boolean watchSubtree = true;
//监听程序Id
int watchId;
//添加到监视队列中
try {
watchId = JNotify.addWatch(rootDir, MASK, watchSubtree, this);
log.info("jnotify -----------启动成功-----------, watchId = {}",watchId);
} catch (JNotifyException e) {
e.printStackTrace();
}
// 死循环,线程一直执行,休眠一分钟后继续执行,主要是为了让主线程一直执行
// 休眠时间和监测文件发生的效率无关(就是说不是监视目录文件改变一分钟后才监测到,监测几乎是实时的,调用本地系统库)
while (true) {
try {
Thread.sleep(60000);
} catch (InterruptedException e) {// ignore it
e.printStackTrace();
Thread.currentThread().interrupt();
}
}
}
@Override
public void fileCreated(int wd, String rootPath, String name) {
log.info("文件被创建, 创建位置为: " + rootPath + "/" + name);
}
@Override
public void fileDeleted(int wd, String rootPath, String name) {
log.info("文件被删除, 被删除的文件名为:" + rootPath + name);
}
@Override
public void fileModified(int wd, String rootPath, String name) {
log.info("文件内容被修改, 文件名为:" + rootPath + "/" + name);
}
@Override
public void fileRenamed(int wd, String rootPath, String oldName, String newName) {
log.info("文件被重命名, 原文件名为:" + rootPath + "/" + oldName
+ ", 现文件名为:" + rootPath + "/" + newName);
}
测试代码:
public class JnotifyTest {
public static void main(String[] args) throws Exception {
String rootDir = "C:\\logs";
new CustomJnotifyAdapter(rootDir).beginWatch();
}
}