Java implementation file change monitoring _java

Source: Internet
Author: User

A. Spring configuration file:

Application.xml

<?xml version= "1.0" encoding= "UTF-8"?> <beans "xmlns=" xmlns: Xsi= "Http://www.w3.org/2001/XMLSchema-instance" xmlns:tx= "Http://www.springframework.org/schema/tx" xmlns:aop= " Http://www.springframework.org/schema/aop "xmlns:context=" Http://www.springframework.org/schema/context "xmlns: Dwr= "Http://www.directwebremoting.org/schema/spring-dwr" xmlns:jaxrs= "Http://cxf.apache.org/jaxrs" xsi: schemalocation= "Http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/ Spring-beans-3.1.xsd Http://www.springframework.org/schema/tx http://www.springframework.org/schema/tx/ Spring-tx-3.1.xsd HTTP://WWW.SPRINGFRAMEWORK.ORG/SCHEMA/AOP http://www.springframework.org/schema/aop/ Spring-aop-3.1.xsd Http://www.springframework.org/schema/context http://www.springframework.org/schema/context/ Spring-context-3.1.xsd Http://www.directwebremoting.org/schema/spring-dwr http://www.directwebremoting.org/ Schema/spring-dwr-3.0.xsd http://Cxf.apache.org/jaxrs http://cxf.apache.org/schemas/jaxrs.xsd "> <!--file monitor--> <bean id=" Monitor "class=" Com.interfaces.file.monitor.FileMonitorImpl "> <constructor-arg index=" 0 "value=" 10000 "/> <!--monitoring time interval, 
Unit: Millisecond--> <constructor-arg index= "1" ref= "Observer"/> <!--file Viewer--> </bean> <!--file Viewer--> <bean id= "Observer" class= "Com.interfaces.file.monitor.FileObserverImpl" > <constructor-arg index= "0" value = "D:\\uploaddir"/> <!--directory--> <constructor-arg index= "1" ref= "filter"/> <!--file filter--> < Constructor-arg index= "2" ref= "Listener"/> <!--file listener--> </bean> <!--file listener--> <bean id= "Listen Er "class=" Com.interfaces.file.monitor.FileListener "/> <!--file filter--> <bean id=" filter "class="
Com.interfaces.file.monitor.FileFilterImpl "> <!--Specify the file name extension, only the specified extension file will be processed. "," intervals between different extensions, such as: Xml,txt,bak--> <constructor-arg index= "0" value= "xml"/> </bean> </Beans> 

Two. Spring Context Load Listener:

Springcontextloaderlistener.class

Import javax.servlet.ServletContextEvent;
Import Org.springframework.web.context.ContextLoaderListener;
public class Springcontextloaderlistener extends contextloaderlistener{
@Override public
Void Contextinitialized (Servletcontextevent event) {
super.contextinitialized (event);
FileMonitor scanner = Getscanner ();
Start directory Scanner
Scanner.start ();
}
@Override public
void contextdestroyed (Servletcontextevent event) {
FileMonitor scanner = Getscanner ();
Close Directory Scanner
scanner.stop ();
Super.contextdestroyed (event);
}
/**
* Get directory Scanner
* @return *
*
private FileMonitor Getscanner () {
return Getcurrentwebapplicationcontext (). Getbean (Filemonitor.class);
}
}

Three. Web project configuration file:

Xml

<?xml version= "1.0" encoding= "UTF-8"?> <web-app xmlns:xsi=
"Http://www.w3.org/2001/XMLSchema-instance" "xmlns:web=" Http://xmlns.jcp.org/xml/ns/javaee "xsi:schemalocation=" Http://java.sun.com/xml/ns/javaee http:// Java.sun.com/xml/ns/javaee/web-app_2_4.xsd Http://xmlns.jcp.org/xml/ns/javaee http://java.sun.com/xml/ns/javaee/ Web-app_2_5.xsd "version=" 2.4 ">
<context-param>
<param-name>contextconfiglocation</ param-name>
<param-value>
classpath:application.xml
</param-value>
</ context-param>
<listener>
<listener-class>com.web.springcontextloaderlistener</ listener-class>
</listener>
</web-app>

Four. File Monitor

 1. Interface: Filemonitor.class

Import Org.apache.commons.io.monitor.FileAlterationObserver;
/**
* File Monitor role/public
interface FileMonitor {
/**
* Registration OBSERVER
* @param observer Observer
* * VOID Addobserver (Filealterationobserver observer);
/**
* Delete Observer
* @param observer observer
/VOID Removeobserver (Filealterationobserver observer); 
/**
* Acquisition of all registered Observer
* @return Observer SET * *
*
iterable<filealterationobserver> getobservers (); 
/**
* Start monitor
/void Start (); 
/**
* Stop monitor
/void Stop (); 
/**
* Obtain monitoring interval
* @return interval (in milliseconds)/
long Getinterval (); 
}

 2. Implementation class: Filemonitorimpl.class

Import Java.util.concurrent.ThreadFactory;
Import Org.apache.commons.io.monitor.FileAlterationMonitor;
Import Org.apache.commons.io.monitor.FileAlterationObserver;
Import Org.apache.commons.lang3.concurrent.BasicThreadFactory; /** * Monitor, monitor time interval, set file Viewer/public class Filemonitorimpl implements filemonitor{private final Filealterationmonitor Monit
Or
/** * Monitor Thread name */private static final String Monitor_thread_name = "File monitor Daemon";
/** * Monitor thread DAEMON mark/private static final Boolean DAEMON = false; /** * Define monitoring time interval, file observer * @param interval monitoring interval * @param observer file observer/FILEMONITORIMPL (int interval, final filealteratio Nobserver observer) {This (interval, observer, new Basicthreadfactory.builder (). Namingpattern (Monitor_thread_name). 
Daemon (daemon). build ());  /** * Define monitoring intervals, file watcher and thread factory * @param interval monitoring interval * @param observer file Viewer * @param factory thread factory/filemonitorimpl (int Interval, Final Filealterationobserver Observer, Final Threadfactory factory) {this.monitor = new Filealterationmonitor (interval, new filealterationobserver[] {observer}); 
Monitor.setthreadfactory (Factory); /** * Add File Viewer * @param observer/@Override public void Addobserver (Filealterationobserver observer) {MONITOR.ADDOBSE
RVER (Observer); /** * Delete File Viewer * @param observer/@Override public void Removeobserver (Filealterationobserver observer) {Monitor.remo
VEOBSERVER (Observer); /** * GET ALL registered Observer * @return/@Override public iterable<filealterationobserver> getobservers () {return monitor.ge
Tobservers (); 
/** * Start monitor/@Override public void Start () {try {Monitor.start ()}
catch (Exception e) {e.printstacktrace ();}} 
/** * Stop monitor/@Override public void Stop () {try {monitor.stop ()}
catch (Exception e) {e.printstacktrace ();}} 
/** * Get monitoring time interval * * @Override public long Getinterval () {return monitor.getinterval ();  }
}

Five. File Viewer

1. Interface: Fileobserver.class

Import Java.io.File;
Import Org.apache.commons.io.monitor.FileAlterationListener;
/**
* File Viewer role/
public
interface Fileobserver {
/**
* Add listener
* @param listener
*
void AddListener (final Filealterationlistener listener);
/**
* Remove listener
* @param listener
/void RemoveListener (final Filealterationlistener listener);
/**
* Get registered Listener * @return * * *
iterable<filealterationlistener> getlisteners (); 
/**
* Initialization Observer
* @throws Exception
/Void Initialize () throws Exception; 
/**
* Destroy Observer
* @throws Exception
/Void Destroy () throws Exception; 
/**
* Access to observation directory
* @return
/File getdirectory ();
/**
* Get file filter * 
* @return
/public
filefilter getfilter ();

 2. Implementation class: Fileobserverimpl.class

Import Java.io.File;
Import java.io.IOException;
Import Org.apache.commons.io.FileUtils;
Import Org.apache.commons.io.IOCase;
Import Org.apache.commons.io.monitor.FileAlterationListener;
Import Org.apache.commons.io.monitor.FileAlterationObserver; /** * File Viewer * * When a file is created, deleted, or changed, the message notifies the listener/public class Fileobserverimpl extends Filealterationobserver implements file observer{private static final long Serialversionuid = -7239227289538993830l/** * File filter/private final FileFilter filt
Er /** * Set the directory to listen for observations, and set up file filters and listeners to observe the file specified with the specified extension * @param dir observation Listener directory * @param filter file filter * @param listener File Listener * * Publi C Fileobserverimpl (String dir, final filefilter filter, Filealterationlistener listener) {Super (dir, filter, (Iocase) nu
ll); 
AddListener (listener);
This.filter = filter;
File directory = new file (dir); 
If the directory does not exist if (!directory.exists ()) {try {fileutils.forcemkdir (directory);}
catch (IOException e) {e.printstacktrace ();}} If there is a file else if (directory.exists () &&
Directory.isfile ()) {try {fileutils.forcedelete (directory);
Fileutils.forcemkdir (directory);
catch (IOException e) {e.printstacktrace ();}} 
/** * Add Listener * * @Override public void AddListener (final Filealterationlistener listener) {Super.addlistener (listener);} /** * Remove listener/@Override public void RemoveListener (final Filealterationlistener listener) {Super.removelistener (listene
R); /** * Get all listeners of the Observer object/@Override public iterable<filealterationlistener> getlisteners () {return super.getlistene
RS (); 
/** * Initialization file observer/@Override public void Initialize () throws Exception {super.initialize ();}/** * Destroy file Observer/@Override public void Destroy () throws Exception {Super.destroy ();}/** * Get the observed directory */@Override public File getdirectory () {Retu
RN Super.getdirectory (); 
/** * Get file filter * @return/public FileFilter GetFilter () {return filter} }

Six. File Listener:

Filelistener.class

Import Java.io.File;
Import Org.apache.commons.io.monitor.FileAlterationListenerAdaptor;
Import Org.apache.commons.io.monitor.FileAlterationObserver;
/**
* File listener/Public
final class Filelistener extends Filealterationlisteneradaptor {
/**
* Action to execute when file is
created
/* @Override public
void onfilecreate (file file) {
/Something
}
/**< C18/>* the action to be performed when the file is deleted (transferred)
* *
@Override public
void onfiledelete (file file) {
//todo Something
}
/**
* The action to be executed when the content of the file is changed * *
@Override public
void Onfilechange (file file) {
//TODO Something
}
/**
* The action to perform when listening is performed *
/@Override public
void OnStart ( Filealterationobserver observer) {
//To do something
}
/**
* action to be performed when stop listening * *
@Override Public
void OnStop (Filealterationobserver observer) {
//todo Something
}
}

Seven. File filter

 1. Interface: Filefilter.class

/**
* File Filter role, extended from Java.io.FileFilter * * Public
Interface FileFilter extends Java.io.FileFilter {
/**
* Get the defined extension
* 
* @return * * *
string[] getextensions ();
}

 2. Implementation class:

Filefilterimpl.class

Import Java.io.File;
Import Org.apache.commons.io.FilenameUtils;
/**
* File filter
/Public
class Filefilterimpl implements filefilter{
private string[] extensions;
Public Filefilterimpl (String ... extensions) {
this.extensions = extensions;
}
/**
* Accept the file *
/@Override public
Boolean accept (file pathname) {
return Filenameutils.isextension (Pathname.getname (), extensions); 
}
/**
* Get the defined extension
* @return * * 
@Override public
string[] getextensions () {
return Extensions
}
}

The above is a small series to introduce you to the implementation of the Java file change monitoring, I hope to help you, if you have any questions please give me a message, small series will promptly reply to everyone. Here also thank you very much for the cloud Habitat Community website support!

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.