Here to write the link content-Watchservice
Public classwatchservicetest { Public Static void Main(string[] args) {Try{Watchservice Watchservice = Filesystems.getdefault (). Newwatchservice (); Paths.Get("d:\\"). Register (Watchservice, Standardwatcheventkinds.entry_create, Standardwatcheventkinds.entry_delete,sta Ndardwatcheventkinds.entry_modify); while(true) {Watchkey key = Watchservice.take (); for(watchevent<?>Event: Key.pollevents ()) {System. out. println (Event. Context () +"It happened."+Event. Kind () +"Events"); } Boolean vaild = Key.reset ();//Reset Watchkey if(!vaild) {//If reset fails, exit monitoring Break; } } }Catch(IOException | Interruptedexception e) {e.printstacktrace (); } }}
Results:
The author uses the D-disk directory for monitoring, this monitor file changes the listener can do to the D disk and its first level of sub-directory changes to listen to its subdirectories within the changes cannot be monitored.
Watchservice has 3 methods to obtain file change events for the warship directory.
Poll (): Gets the next Watchkey and returns null immediately if no watchkey occurs.
Poll (long timeout, timeunit unit): Try to wait for timeout time to get the next watchkey.
Take (): Gets the next watchkey if no watchkey occurs on the transplant wait.
If the program needs to be monitored all the time, select the Take () method. If the program needs to listen for a specified time, use the poll () method.
- Accessing file properties
Public classattributeviewtest { Public Static void Main(string[] args) {Path Testpath = Paths.Get(". \\src\\com\\yin\\nio\\AttributeViewTest.java"); Basicfileattributeview Basicview = Files.getfileattributeview (Testpath, Basicfileattributeview.class);Try{Basicfileattributes basicfileattributes = basicview.readattributes (); PRINTSTR ("Creation time:"+NewDate (Basicfileattributes.creationtime (). Tomillis ()). toLocaleString ()); PRINTSTR ("Last Access time:"+NewDate (Basicfileattributes.lastaccesstime (). Tomillis ()). toLocaleString ()); PRINTSTR ("Last modified:"+NewDate (Basicfileattributes.lastmodifiedtime (). Tomillis ()). toLocaleString ()); PRINTSTR ("File size:"+basicfileattributes.size ()); }Catch(IOException e) {E.printstacktrace (); } }Private Static void Printstr(String str) {System. out. println (str); }}
Results:
SOURCE download
Java NiO Detailed and examples and source code download (ii)