Monitor file changes in a directory via Java __java

Source: Internet
Author: User

Recently addressed a requirement, this is probably the case: set up the FTP server to the other side of the server to the designated directory (assuming that directory a) upload files on the other side need to transfer good files (in the state of upload file can not be processed) resolved and updated to the database of directory a only Read permission, that is, you cannot delete, rename, or move files in directory A.

For this demand, the solution I started out with was to open a thread and periodically read all the files in directory A to compare the list of files that were read every two times, and the new file name corresponds to the new file that was uploaded by the other party, first recording its size and The last modification time , then, every 2 seconds, to read it again the values of these two properties. If the two values remain the same, then the file is sent on. If there is a change, then 2 seconds to determine again. After you make sure the file is uploaded, parse the file and update it to the database

This program is generally capable of being competent, but it hides the following two small problems: Read the interval of directory A is not too good settings, set small, will make the frequency of reading too often, set large, and may result in a large backlog of file size and the last modification time the interval between the values of these two properties is also not OK, it says 2 seconds, which is my own assumption. Because when you encounter a large file, it is very likely that within 2 seconds will not pass. If FTP is built on the Windows operating system, there will be the following problem:
A file at the beginning of the transmission, the size of the file has been determined, in the transmission process, through the Java File Class Lengh () to view the words, its value will not change.
For the last modification of this property, only at the beginning of the file creation and file transmission after the transfer, will be changed, in the transmission process, through the Java File Class Lastmodifiedtime () to view the words, it will not change the value of If the FTP is built on the Unix operating system, there is no above this problem, in the entire file transfer process, the size and the last modification time These two attributes are always changing. (I have verified it on the CentOS7)

Since the above plan is flawed, think of other options.
Later, under the inspiration of colleagues, found the JDK7 added new Api:file Watch Service.

The idea of this API, in fact, is the same as the Observer Model: Register a watcher for the specified directory, when the file changes in the directory, Java notify you this watcher said file changes. That way, you can handle it.

The following direct code:

Import Java.io.File;
Import java.io.IOException;
Import Java.nio.file.FileSystems;
Import Java.nio.file.Path;
Import java.nio.file.Paths;
Import java.nio.file.WatchEvent;
Import Java.nio.file.WatchKey;
Import Java.nio.file.WatchService;

Import static java.nio.file.standardwatcheventkinds.*;

    public class Sample {private Watchservice watcher;

    private path Path;
        Public Sample (path path) throws IOException {this.path = path;
        Watcher = Filesystems.getdefault (). Newwatchservice ();
    This.path.register (Watcher, OVERFLOW, Entry_create, Entry_delete, entry_modify); The public void Handleevents () throws Interruptedexception {//start to process the data files while

            true) {//start to handle the ' File Change event final Watchkey key = Watcher.take (); For (watchevent<?> event:key.pollEvents ()) {//Get event type final watchevent. kind<?> Kind = event.kind (); Get file name @SuppressWarnings ("unchecked") Final watchevent<path> Pathwatcheven
                t = (watchevent<path>) event;

                Final Path fileName = Pathwatchevent.context (); if (kind = = Entry_create) {//Description point 1//CREATE a new thread to monitor the new fil
                            E New Thread (new Runnable () {public void run () {
                            File File = new file (Path.tofile (). GetAbsolutePath () + "/" + fileName);
                            Boolean exist;
                            Long size = 0;
                            Long lastmodified = 0;
                            int samecount = 0; while (exist = File.exists ()) {//If the ' size ' and ' lastmodified ' attribute keep same fo R 3 times,//Then we are the file was transferred successfully if (size = = File.length () && lastmodified = = file.lastmodified ()) {
                                    if (++samecount >= 3) {break;
                                    } else {size = File.length ();
                                LastModified = File.lastmodified ();
                                try {thread.sleep (500);
                                catch (Interruptedexception e) {return;
                            }//If the new file was cancelled or deleted
                            if (!exist) {return;
               else {//update database ...             }}). Start ();
                    else if (kind = = Entry_delete) {//Todo} else if (kind = = Entry_modify) {
            TODO} else if (kind = OVERFLOW) {//Todo} }//Important:the key must be reset after processed if (!key.reset ()) {Retu
            Rn }} public static void Main (String args[]) throws IOException, interruptedexception {new Sampl
    E (Paths.get (Args[0])). Handleevents ();
 }
}

For " description point 1" in the above code, add the following: This is explained by the fact that the file size and the last modification time of the file are limited to the Unix operating system. For Windows systems, you should continue listening after the entry_create event is generated, until a "entry_modify" event occurs for that file, or the entry_delete event To indicate that the file was transmitted or canceled. Embedded Thread is better to build another class, so it will look easier to understand.

Reference documentation

Oracle Official Example

Related Article

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.