Implement features like. NET Filewatcher with the monitoring service (Watchservice API) that comes with Java SE 7

Source: Internet
Author: User
Tags assert java se

Transferred from: http://www.cnblogs.com/callwangxiang/archive/2011/08/04/JavaDirectoryWatcherFileWatcher.html

A sample of monitoring directory Changes was added to the Java SE 7 tutorial to describe its newly released Watchservice API.

But for a user accustomed to the. NET Filewatcher, I think it has two deficiencies if you use it for a project:

1, should provide a separate thread background operation mechanism, so that the monitoring process itself in the background, does not affect the front-end processing

2. Java does not have a built-in source event mechanism like. NET, but can use its built-in Observer/observable object to implement quasi-events with observer patterns

Here is the Java SE Tutorial example to remove extraneous content, to supplement the above two extensions after the implementation, because this API is relatively new, but also hope to discuss with you a lot:

1, reference. NET defining event Parameter objects

 Packagemarvellousworks.practicalpattern.concept.unittest;ImportJava.nio.file.WatchEvent.Kind;/*** File System event Type *@authorWangxiang **/ Public Final classFileSystemEventArgs {Private FinalString FileName; Private FinalKind<?>kind;  PublicFileSystemEventArgs (String fileName, kind<?>kind) {         This. FileName =FileName;  This. Kind =kind; }        /*** Path of the file*/     PublicString GetFileName () {returnFileName;} /*** Operation type: change, create, delete*/@SuppressWarnings ("Rawtypes")     PublicKind Getkind () {returnkind;}}

2, the definition of directorywatcher, for monitoring a folder, as to how to extend the Filewatcher can be on this basis by qualifying the file name and operation type of way to expand

 Packagemarvellousworks.practicalpattern.concept.unittest;Importjava.io.IOException;ImportJava.nio.file.FileSystems;ImportJava.nio.file.Path;Importjava.nio.file.Paths;Importjava.nio.file.WatchEvent;ImportJava.nio.file.WatchEvent.Kind;ImportJava.nio.file.WatchKey;ImportJava.nio.file.WatchService;Importjava.util.Observable;Importjava.util.concurrent.Callable;ImportJava.util.concurrent.Executor;Importjava.util.concurrent.Executors;ImportJava.util.concurrent.FutureTask;Import Staticjava.nio.file.standardwatcheventkinds.*;/*** Monitor updates, create and delete events for files within a directory (excluding subdirectories) * * for http://download.oracle.com/javase/tutorial/essential/io/ Notification.html was remodeled * to bring it closer. NET directorywatcher Use habits * * Because Java does not resemble. NET source Event mechanism * Therefore implemented on the implementation of the Java SE comes with the Observer/observable object thrown out "false" event * * Suitable for Java SE 7 * *@authorWangxiang **/ Public classDirectorywatcherextendsobservable{PrivateWatchservice watcher; Privatepath Path; PrivateWatchkey Key; PrivateExecutor Executor =Executors.newsinglethreadexecutor (); Futuretask<Integer> task =NewFuturetask<integer>(            NewCallable<integer>(){                 PublicInteger Call ()throwsinterruptedexception{processevents (); returnInteger.valueof (0);}}); @SuppressWarnings ("Unchecked")    Static<T> watchevent<t> Cast (watchevent<?>event) {        return(watchevent<t>) event; }     PublicDirectorywatcher (String dir)throwsIOException {Watcher=Filesystems.getdefault (). Newwatchservice (); Path=Paths.get (dir); //monitor updates, create, and delete events for files within a directoryKey =Path.register (Watcher, Entry_modify, Entry_create, Entry_delete); }    /*** Start the monitoring process*/     Public voidExecute () {//start an additional thread preempted watching process through the thread poolExecutor.execute (Task); }        /*** The object cannot be restarted after closing *@throwsIOException*/     Public voidShutdown ()throwsIOException {watcher.close (); Executor=NULL; }    /*** Monitor File system events*/    voidprocessevents () { while(true) {            //wait until the event signal is obtainedWatchkey Signal; Try{signal=Watcher.take (); } Catch(Interruptedexception x) {return; }             for(watchevent<?>event:signal.pollEvents ()) {Kind<?> kind =Event.kind (); //Tbd-provide Example of how OVERFLOW event is handled                if(Kind = =OVERFLOW) {                    Continue; }                //Context for directory entry event is the file name of entrywatchevent<path> ev =cast (event); Path name=Ev.context ();            Notifiy (Name.getfilename (). ToString (), kind); }            //prepare for monitoring the next notificationKey.reset (); }    }        /*** Notify external Observer directory for new event updates*/    voidNotifiy (String fileName, kind<?>kind) {        //the label directory has been changedsetchanged (); //Proactive notification of changes to the state of individual observers ' target objects//The "Push" mode of the Observer pattern is used here.Notifyobservers (NewFileSystemEventArgs (fileName, kind)); }}

3. Unit Test

 PackageCom.ieslab.web.tool;Import StaticJava.nio.file.StandardWatchEventKinds.ENTRY_CREATE;ImportJava.io.File;Importjava.io.IOException;Importjava.util.ArrayList;Importjava.util.List;Importjava.util.Observable;ImportJava.util.Observer;ImportOrg.junit.Assert;Importorg.junit.Test; Public classDirectorywatcherfixture {Private Static FinalString Dir_path =system.getproperty ("User.dir"); Private Static FinalFile DIR =NewFile (Dir_path); Private Static FinalString SUFFIX = ". txt"; Private Static FinalString PREFIX = "Test"; Private Static Final intAdd_times = 3; /*** Viewer *@authorWangxiang **/     Public classLoggerImplementsobserver{@Override Public voidUpdate (Observable Observable, Object eventArgs) {FileSystemEventArgs args=(FileSystemEventArgs) EventArgs; System.out.printf ("%s has been%s\n", Args.getfilename (), Args.getkind ());            Assert.asserttrue (Args.getfilename (). StartsWith (PREFIX));        Assert.assertequals (Entry_create, Args.getkind ()); }} @Test Public voidTestwatchfile ()throwsIOException, interruptedexception{Directorywatcher watcher=NewDirectorywatcher (Dir_path); Logger L1=NewLogger ();        Watcher.addobserver (L1);                Watcher.execute (); //Create a series of temporary fileslist<string> files =NewArraylist<>();  for(inti=0; i<add_times; i++) {Files.add (File.createtempfile (PREFIX, SUFFIX, DIR). toString ()); }                //delay waiting for background tasks to executeThread.Sleep (4000);        Watcher.shutdown (); System.out.println ("Finished"); }}

Test content displayed in the console window

Test5769907807190550725.txt has been entry_create
Test4657672246246330348.txt has been entry_create
Test1823102943601166149.txt has been entry_create
Finished

(go) Implement a feature similar to. NET Filewatcher with the monitoring service (Watchservice API) that comes with Java SE 7

Related Article

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.