Java NIO2-Watching Service API

1) NIO2 Introduced new Mechanism to read a File.

                           Path path=Paths.get ("F:\\niotestfiles\\one.txt");

2)The Watch Service API was introduced in Java 7 (NIO.2) as a thread-safe service that is capable of
watching objects for changes and events.

3)Watch Service API Classes
                         A)java.nio.file.WatchService interface
                         B)java.nio.file.Watchable interface
                         C)java.nio.file.StandardWatchEventKinds class
                         D)WatchEvent.Kind interface.

A)WatchService: It is the Starting Point of this API.
              
               WatchService watchService = FileSystems.getDefault().newWatchService();

B)StandarWatchEventKinds: 
               
                  a)StandardWatchEventKinds.ENTRY_CREATE:It is triggered when a file is renamed or moved into this directory.
                  b)StandardWatchEventKinds.ENTRY_DELETE:Renamed or moved.
                  c)StandardWatchEventKinds.ENTRY_MODIFY:Modified
                  d)StandardWatchEventKinds.OVERFLOW:Events might have been lost.


final Path path = Paths.get("C:/rafaelnadal");
WatchService watchService = FileSystems.getDefault().newWatchService();
path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
watchService.close();

WatchService contains the below methods

poll():If No key is available it returns null value.
take():If no key is available,it waits until a key is queued.

1)Steps to Develop the watching API.

              a)First Give the Path  of Directory.
                       Path path=Paths.get("F:\\niotestfiles");
              b)Watching service,
                       WatchService watchService=FileSystems.getDefault().newWatchService()
              c)Register the path
                       path.register(watchService, StandardWatchEventKinds.ENTRY_CREATE,
StandardWatchEventKinds.ENTRY_MODIFY, StandardWatchEventKinds.ENTRY_DELETE);
              d)Now start the infinite loop with while(true) or for(;;).
                          a)Key Watch
                                   final WatchKey watchKey=watchService.take();
                          b)Poll Events.
                                   watchKey.pollEvents()
                          c)What kind of events are done 
                                     final Kind kind=events.kind();
                                    


Comments