1. thread round robin Scanning
Advantages: pure Java implementation, perfect cross-platform.
Disadvantage: when many listening files exist, the amount of scanning is too large. The response is not very timely and relies on the scanning interval.
2. File hook
Advantages: event-driven mode, no directory scan.
Disadvantages: Platform-related
The jnotify development kit is a good file hook library, which is used as follows:
Public class fiemonitor
{
/**
* @ Param ARGs
*/
Public static void main (string [] ARGs)
{
String monitedpath = "E:/templete ";
Int mask = jnotify. file_created | jnotify. file_deleted | jnotify. file_modified | jnotify. file_renamed;
// Monitor sub-Directories
Boolean watchsubtree = true;
Try {
Int watchid = jnotify. addwatch (monitedpath, mask, watchsubtree, new listener ());
Thread. Sleep (1000000 );
Boolean res = jnotify. removewatch (watchid );
If (! Res)
{
// Invalid
}
} Catch (exception E)
{
E. printstacktrace ();
}
}
Public static class listener implements jpolicylistener
{
Public void filerenamed (int wd, string rootpath, string oldname, string newname)
{
Print ("renamed" + rootpath + ":" + oldname + "->" + newname );
}
Public void filemodified (int wd, string rootpath, string name)
{
Print ("modified" + rootpath + ":" + name );
}
Public void filedeleted (int wd, string rootpath, string name)
{
Print ("deleted" + rootpath + ":" + name );
}
Public void filecreated (int wd, string rootpath, string name)
{
Print ("created" + rootpath + ":" + name );
}
Void print (string MSG)
{
System. Err. println (MSG );
}
}
}
Note: A rename file under Win generates two Rename and modify events.
This library also has a disadvantage: I have to add the dependent DLL (JY Y. dll/jnotify_64bit.dll) under java. Library. path, which makes me very uncomfortable. Follow up the source code and find that it is used
System. loadlibrary ("jnotify ")
No wonder. Change it to system. Load ("xxxx/jnotify. dll"), and repackage DLL, so, and other files and class files into a jar!