Sunday, June 15, 2014
Today in this article I will discuss with an amazing feature of Java7. Here I will show you how to create a file/folder watcher/watch service. In other words I will actually write Java code which will be able to monitor a file/folder/directory for changes. This will require Java 7 NIO .2. This monitoring service is very useful in many applications like IDE. Also this can be used for hot deployment in servers. Monitoring or watching a folder for changes means that whenever there is a change in file system associated with the folder then an event is triggerd. The event is catched and associated change is extracted to know what change has occurred and based on that different actions can be taken.
Below are the steps you must follow to implement watch service
1. Get the path of the folder - The first step is to get the Path object associated with the folder. This is done using Paths.get() method.
2. Get file system of the path - Next step is to get the FileSystem object associated with the Path object. This is done using getFileSystem() method.
3. Get watch service - Next you have to get WatchService from FileSystem object using newWatchService() method.
4. Register to watch service and events - In this step you will have to register the Path object to the watch service created. With that you will also have to mention all the events that you want to monitor. There are four events ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW. This is done using register() method.
5. Start infinite loop - You will have top start the infinite loop to watch the folder continously.
5a. Poll the events for watch key - Inside the loop you will have to poll for events using pol() or take() methods. Though there are two poll methods but its is better sometimes to use take method as it waits until an event occurs, whereas for poll methods they return null value so you have to keep a null check otherwise NullPointer Exception will be thrown.
5b. Retrieve pending events - Next you have to retrieve the pending events. There can be more than one event, so use a for loop and get events from WatchKey. Depending on event take necessary actions.
5c. Reset the key - Next reset the key and wait for next events using reset() method.
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Below are the steps you must follow to implement watch service
1. Get the path of the folder - The first step is to get the Path object associated with the folder. This is done using Paths.get() method.
2. Get file system of the path - Next step is to get the FileSystem object associated with the Path object. This is done using getFileSystem() method.
3. Get watch service - Next you have to get WatchService from FileSystem object using newWatchService() method.
4. Register to watch service and events - In this step you will have to register the Path object to the watch service created. With that you will also have to mention all the events that you want to monitor. There are four events ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY, OVERFLOW. This is done using register() method.
5. Start infinite loop - You will have top start the infinite loop to watch the folder continously.
5a. Poll the events for watch key - Inside the loop you will have to poll for events using pol() or take() methods. Though there are two poll methods but its is better sometimes to use take method as it waits until an event occurs, whereas for poll methods they return null value so you have to keep a null check otherwise NullPointer Exception will be thrown.
5b. Retrieve pending events - Next you have to retrieve the pending events. There can be more than one event, so use a for loop and get events from WatchKey. Depending on event take necessary actions.
5c. Reset the key - Next reset the key and wait for next events using reset() method.
-------------------------------------------------------------------------------------------------------------------------
Java Source Code
-------------------------------------------------------------------------------------------------------------------------import java.nio.file.FileSystem; import java.nio.file.Path; import static java.nio.file.StandardWatchEventKinds.*; import java.nio.file.Paths; import java.nio.file.WatchEvent; import java.nio.file.WatchKey; import java.nio.file.WatchEvent.Kind; import java.nio.file.WatchService; import java.util.concurrent.TimeUnit; public class FolderMonitor { /** * Monitors a folder for changes * @param path Path to be monitored * @throws Exception */ public void monitor(Path path) throws Exception{ FileSystem fs = path.getFileSystem(); //get file system try(WatchService ws = fs.newWatchService()){ //get watch service in try block //register for events to warch service path.register(ws, ENTRY_CREATE, ENTRY_DELETE, ENTRY_MODIFY); System.out.println("Watching : "+path); while(true){ //poll loop final WatchKey key = ws.take(); //wait and get watch key for(WatchEvent<?> we : key.pollEvents()){ final Kind<?> kind = we.kind(); //get event kind if(kind == OVERFLOW) return; else if(kind == ENTRY_CREATE) printEvent("New path created", we); else if(kind == ENTRY_DELETE) printEvent("Path deleted", we); else if(kind == ENTRY_MODIFY) printEvent("Path modified", we); } if(!key.reset()) //reset break; } } } /** * Displays event occurred * @param desc Description of event * @param we watch event */ private void printEvent(String desc, WatchEvent<?> we){ System.out.println(desc+" : "+((WatchEvent<Path>)we).context()); } public static void main(String[] args) throws Exception { FolderMonitor fm = new FolderMonitor(); fm.monitor(Paths.get("C:/demo")); } }-------------------------------------------------------------------------------------------------------------------------
Download Links
-------------------------------------------------------------------------------------------------------------------------
DOWNLOAD the source from Mediafire
DOWNLOAD the source from 4shared
Labels:Files
Subscribe to:
Post Comments
(Atom)
Total Pageviews
Followers
Labels
- Algorithms (7)
- Annotation (3)
- Files (6)
- Generics (3)
- Graphics2D (5)
- Graphics2D-Images (7)
- Inheritance (2)
- J2EE (9)
- Java 8 (4)
- Java FAQs (19)
- JDBC (3)
- Networking (2)
- Packages (1)
- Reflection (4)
- Security (7)
- Sorting (2)
- Swing (3)
- Threads (3)
- Utils (3)
Popular Posts
-
Today I will show you how you can implement Bankers algorithm in Java. The Banker's algorithm is a resource allocation and deadlock a...
-
------------------------- UPDATE ------------------------- I have updated the code on request of some followers so that they can directly...
-
Today I am going to show how to convert a postfix expression to an infix expression using stack in Java. In an earlier post here we ...
-
Today in this article I will tell you how to convert an infix expression to postfix expression using stack. This is an important applicat...
-
--------------------UPDATE------------------- I have updated my post so that now it can detect IE 11. This modification was necessary as t...
-
Today I am going to show you how you can generate and validate captcha. A CAPTCHA (an acronym for "Completely Automated Public Turin...
-
Today I am going to post a program that will be able to produce all the mColorings of a given graph G. What is mColoring : The problem st...
-
Today in this article I will show you how to create or develop a Tower of Hanoi game in Java. The Tower of Hanoi is a famous problem tha...
0 comments:
Post a Comment