Java implementation of directory file monitoring instance code

Source: Internet
Author: User

Versions earlier than Java 7 do not have native support. Let's talk about the solution of JDK 1.7 and earlier:

Event-driven approach, without having to perform directory scans, but related to the platform
Thread round-robin scanning, implemented in java only, perfect cross-platform, but with a large number of listening files, the scanning volume is too large, and the response is not very timely, depending on the scanning interval

JNotify is event-driven, so the processing methods for different platforms are different. Therefore, you need to add jy y. dll/jnotify_64bit.dll in java. library. path. The simplest solution is to directly modify the code. The System. loadLibrary of lines 47 and 51 of jpolicy_win32.java is changed to System. load (dllpath), and the changes on other platforms are also the same. Then, export the dll and so files into a jar package, and the world will be quiet.

The example code is as follows:

The code is as follows: Copy code

Public static void main (String [] args) throws InterruptedException, IOException {
String dir = new File (args. length = 0? ".": Args [0]). getCanonicalFile (). getAbsolutePath ();
JNotify. addWatch (dir, FILE_ANY, true, new jpolicylistener (){
Public void fileRenamed (int wd, String rootPath, String oldName, String newName ){
System. out. println ("renamed" + rootPath + ":" + oldName + "->" + newName );
  }
 
Public void fileModified (int wd, String rootPath, String name ){
System. out. println ("modified" + rootPath + ":" + name );
  }
 
Public void fileDeleted (int wd, String rootPath, String name ){
System. out. println ("deleted" + rootPath + ":" + name );
  }
 
Public void fileCreated (int wd, String rootPath, String name ){
System. out. println ("created" + rootPath + ":" + name );
  }
});
 
System. err. println ("Monitoring" + dir + ", ctrl + c to stop ");
While (true)
Thread. sleep (10000 );
}

Jpathwath has more code to write. For event description, refer to this. A simple example is as follows:

The code is as follows: Copy code

Public static void main (String [] args ){
WatchService watchService = FileSystems. getDefault (). newWatchService ();
Path watchedPath = Paths. get ("E:/temp ");
Try {
WatchKey key = watchedPath. register (watchService, StandardWatchEventKind. ENTRY_MODIFY );
System. out. println (key. isValid ());
} Catch (UnsupportedOperationException uox ){
System. err. println ("file watching not supported! ");
} Catch (IOException iox ){
System. err. println ("I/O errors ");
 }
For (;;){
// Take () will block until a file has been created/deleted
WatchKey signalledKey;
Try {
SignalledKey = watchService. take ();
} Catch (InterruptedException ix ){
Continue;
} Catch (ClosedWatchServiceException cwse ){
System. out. println ("watch service closed, terminating .");
Break;
  }
 
List <WatchEvent <?> List = signalledKey. pollEvents ();
 
SignalledKey. reset ();
For (WatchEvent <?> E: list ){
String message = "";
If (e. kind () = StandardWatchEventKind. ENTRY_MODIFY ){
Path context = (Path) e. context ();
Message = context. toString () + "modified ";
   }
System. out. println (message );
  }
 }
}

Note that on Windows, renaming a file produces two events-renaming and modification. You must pay attention to this when processing the event.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.