---
title: "java监听文件目录的改变"
author: "sd8089730"
date: "2012-07-23T14:33:16Z"
tags: []
categories: ["Web前端"]
slug: "java"
draft: false
lastmod: "2012-07-23T14:45:34Z"
id: 1604262
url: "https://sd8089730.iteye.com/blog/1604262"
---

原文转至：[http://marshal.easymorse.com/archives/1617](http://marshal.easymorse.com/archives/1617)

 JDK 7 oracle 文章地址：[http://docs.oracle.com/javase/tutorial/essential/io/notification.html](http://docs.oracle.com/javase/tutorial/essential/io/notification.html)

 

目前为止，java没有提供自带的对文件目录改变的监听器。使用java自带的（如果是native的就更好了）会方便很多。

这要等到java 7的出现，见：[http://tech.puredanger.com/java7#jsr203](http://tech.puredanger.com/java7#jsr203)，jsr203对io的新扩展中，有：

> A new filesystem interface that supports bulk access to file attributes, ***change notification***, …

但是，目前一般的做法还是自己启动线程定时监控变化。带来的问题是目录文件和嵌套过多的时候性能会下降。

 

网上有一个现成的解决方案，提供了源代码下载：

> [http://twit88.com/blog/2007/10/02/develop-a-java-file-watcher/](http://twit88.com/blog/2007/10/02/develop-a-java-file-watcher/)

可以简单的调用该类库，以下是每5秒钟监控一下指定目录的变化的示例：

> public static void main(String\[] args) {  
> // Monitor c:/temp every 5 seconds  
> DirectoryWatcher dw = new DirectoryWatcher(“c:/temp/”, 5);  
> dw.addListener(new FileListener());  
> dw.start();

其中的FileListener就是自定义的文件监听器。需要实现接口：

> com.lightspeedleader.directorywatcher.IFileListener

可实现的方法包括：

> /\**  
> * Monitoring has just started on this new resource.  
> *  
> * @param monitoredResource the resource now being monitored.  
> \*/  
> public void onStart(Object monitoredResource);
> 
> /\**  
> * Monitoring has just ended on this new resource.  
> *  
> * @param notMonitoredResource the resource not being monitored anymore.  
> \*/  
> public void onStop(Object notMonitoredResource);
> 
> /\**  
> * Something has been added to this resource, or the resource itself has  
> * been added.  
> *  
> * @param newResource the new resource  
> \*/  
> public void onAdd(Object newResource);
> 
> /\**  
> * The resource has been changed.  
> *  
> * @param changedResource the changed resource  
> \*/  
> public void onChange(Object changedResource);
> 
> /\**  
> * Something has been added to this resource, or the resource itself has  
> * been added.  
> *  
> * @param deletedResource the deleted resource  
> \*/  
> public void onDelete(Object deletedResource);  
> }

作者也给出了一个简单的实现：

> public class FileListener extends BaseListener implements IFileListener {
> 
> /\**  
> * Connstructor  
> \*/  
> public FileListener() {  
> super();  
> }
> 
> public void onStart(Object monitoredResource) {  
> // On startup  
> if (monitoredResource instanceof File) {  
> File resource = (File) monitoredResource;  
> if (resource.isDirectory()) {
> 
> System.out.println(“Start to monitor ” + resource.getAbsolutePath());
> 
> /\*File\[] files = resource.listFiles();  
> for (int i = 0; i &lt; files.length; i++) {  
> File f = (File) files\[i];  
> onAdd(f);  
> }\*/  
> }  
> }  
> }
> 
> public void onStop(Object notMonitoredResource) {
> 
> }
> 
> public void onAdd(Object newResource) {  
> if (newResource instanceof File) {  
> File file = (File) newResource;  
> if (file.isFile()) {  
> System.out.println(file.getAbsolutePath() + ” is added”);  
> }  
> }  
> }
> 
> public void onChange(Object changedResource) {  
> if (changedResource instanceof File) {  
> File file = (File) changedResource;  
> if (file.isFile()) {  
> System.out.println(file.getAbsolutePath() + ” is changed”);  
> }
> 
> }  
> }
> 
> public void onDelete(Object deletedResource) {  
> if (deletedResource instanceof String) {  
> String deletedFile = (String) deletedResource;  
> System.out.println(deletedFile + ” is deleted”);  
> }  
> }  
> }

为了使用方便，将该源代码未作任何改动，部署到个人的repository上，可在maven中引用：

> &lt;dependency&gt;  
> &lt;groupId&gt;com.lightspeedleader&lt;/groupId&gt;  
> &lt;artifactId&gt;directorywatcher&lt;/artifactId&gt;  
> &lt;version&gt;1.0&lt;/version&gt;  
> &lt;/dependency&gt;

监听器程序启动线程监控目录，如果不再使用，应该予以关闭：

> dw.stop();

如果是在web系统中使用，应该通过web应用监听器：

> javax.servlet.ServletContextListener

的[contextInitialized](http://tomcat.apache.org/javax/servlet/ServletContextListener.html#contextInitialized%28javax.servlet.ServletContextEvent%29)方法启动文件监听器，通过[contextDestroyed](http://tomcat.apache.org/javax/servlet/ServletContextListener.html#contextDestroyed%28javax.servlet.ServletContextEvent%29)方法关闭文件监听器。

有关该监听器的用法，见：

> [http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContextListener.html](http://tomcat.apache.org/tomcat-5.5-doc/servletapi/javax/servlet/ServletContextListener.html)