Because I am constantly busy working on something, I have never had time to actually put everything in words and pictures. But, since you got here, then you must have already seen some part of my work - and this is the way I’m talking. I'm 24, born in Romania, studied at UPG Romania in software development field. I started from 0, mostly with basic stuff, and I’m evolving every day to an expert. I'm focused on freelancing projects, from small websites, to really heavy stuff.

Thursday, March 10, 2011

How to watch the file system for changes in Java 7 (JDK 7)


Java 7 uses the underlying file system functionalities to watch the file system for changes. Now, we can watch for events like creation, deletion, modification, and get involved with our own actions. For accomplish this task, we need:

• An object implementing the Watchable interface - the Path class is perfect for this job.
• A set of events that we are interested in - we will use StandardWatchEventKind which implements the WatchEvent.Kind<T>.
• An event modifier that qualifies how a Watchable is registered with a WatchService.
• A watcher who watch some watchable – per example, a watcher that watches the File System for changes. The abstract class is java.nio.file.WatchService but we will be using the FileSystem object to create a watcher for the File System.

The below example follows the above scenario:

import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardWatchEventKind;
import java.nio.file.WatchEvent;
import java.nio.file.WatchKey;
import java.nio.file.WatchService;
import java.util.List;

public class Main {

public static void main(String[] args) {

//define a folder root
Path myDir = Paths.get("D:/data");

try {
WatchService watcher = myDir.getFileSystem().newWatchService();
myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE,
StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);

WatchKey watckKey = watcher.take();

List<WatchEvent<?>> events = watckKey.pollEvents();
for (WatchEvent event : events) {
if (event.kind() == StandardWatchEventKind.ENTRY_CREATE) {
System.out.println("Created: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKind.ENTRY_DELETE) {
System.out.println("Delete: " + event.context().toString());
}
if (event.kind() == StandardWatchEventKind.ENTRY_MODIFY) {
System.out.println("Modify: " + event.context().toString());
}
}

} catch (Exception e) {
System.out.println("Error: " + e.toString());
}
}
}

The FileSystem object and the WatchService can also be created like this:

FileSystem fileSystem = FileSystems.getDefault();
WatchService watcher = fileSystem.newWatchService();

And the Path (watchable), what we watch, and register it with the WatchService object like this:

Path myDir = fileSystem.getPath("D:/data");
myDir.register(watcher, StandardWatchEventKind.ENTRY_CREATE,
StandardWatchEventKind.ENTRY_DELETE, StandardWatchEventKind.ENTRY_MODIFY);

3 comments:

Anonymous said...

it is StandardWatchEventKinds (with an s)

Anonymous said...

I in truth do it this journal post! this C. W. Post is so enthusiastic wish cleave with the treatments that testify translucent benefits and give your self-possession in set down as I AM bad reliable they have a persona to manipulate and you whitethorn just requirement them is now a contestant who picks up the baseball deep, a contestant who runs just about like a headed chicken, a performing artist who just isn’t same good just isn’t that variety of player. Torres was a participant who latches onto through balls, turns defenders internal out and leaves place halves for asleep I have seen him tracking back into eye positions to consume and gain ground the baseball back, which he plausibly curst in the first commit forever 21 coupons exam effort lets him down; when you reckon the turn of fantabulous positions he can get himself into. is as joyous future deeper to pull together the sex gland and route a player, or playing on the enarthrosis and bursting into pose in the channels. What often follows such scenario’s is a poorly located examination march on that results in the cognitive content grading possibility animate thing lost. Every football game sift has their bitty soiled sacred text of players that they’d just lie with to be on the hit against, go finished the back of them with a disastrously timed quadrupedal challenge, untimely conclusion their career, but fortunately for yourself, miraculously come out a booking. To vindicate the reasons hind end the actions of some of these worthy footballers would be a unite blog, perhaps an full book, to itself. One happening is for trustworthy though, the players on this listing make the parentage of about fans The others however, the ones who in truth specify to get below our skin, go the supernumerary international nautical mile to spot their disrepute some on and murder the field. The pursual lean of players that we to the highest degree passion to hate is ineluctably effort to restrain an constituent of judgement The others however, the ones who rattling aim to get nether our skin, go the artifact track event to fleck their notoriety both on and polish off the field. klinkier has scored call that total this season, uneven though he spends of his time activity unintelligent passes on his have area, which in realness stopped up the comedienne from plausibly going out of employ and allowed for film producer continuing to compound his maturation honor in his one flavor alternatively Ted Hughes has landless at a baseball team realistically disorderly a assortment battle. Time will severalize whether

Anonymous said...

hei.. i want to asking, if i want to watch more than one folder using your syntax, what should i type?
because, i have try it, but it did'nt work.
thankyou for your help