Java method to determine whether a file has been updated over a period of time

  • 2020-04-01 03:38:23
  • OfStack

This article illustrates a Java method for determining whether a file is updated over a period of time. Share with you for your reference. The specific implementation method is as follows:

Timer 1.

private Timer timer;  
 
/**
* Simple timer
* @param delay  How long before the implementation. ms
* @param period Time between executions. ms
*/ 
public void test(long delay, long period) { 
        timer = new Timer(); 
        timer.schedule(new TimerTask() { 
            public void run() { 
                //How you do it & NBSP; < br / >                 System.out.println(System.currentTimeMillis()); 
            } 
        }, delay, period); 
}

2. Deepen the version

package classloader;  
/**
 * @author vma
 */ 
//Customize a classloader & NBSP; < br / > public class DynamicClassLoader extends ClassLoader { 
    public Class<?> findClass(byte[] b) throws ClassNotFoundException { 
        return defineClass(null, b, 0, b.length); 
    }  package classloader; 
import java.io.File; 
import java.io.FileInputStream; 
import java.io.IOException; 
/**
 * @author vma
 */ 
public class ManageClassLoader { 
    DynamicClassLoader dc =null;      Long lastModified = 0l; 
    Class c = null; 
    //Load the class, if the class file has been loaded, if not, return the current & NBSP; < br / >     public Class loadClass(String name) throws ClassNotFoundException, IOException{ 
     if (isClassModified(name)){ 
        dc =  new DynamicClassLoader(); 
      return c = dc.findClass(getBytes(name)); 
     } 
     return c; 
    } 
    //Whether the judgment has been modified & NBSP; < br / >     private boolean isClassModified(String filename) { 
        boolean returnValue = false; 
        File file = new File(filename); 
        if (file.lastModified() > lastModified) { 
            returnValue = true; 
        } 
        return returnValue; 
    } 
       //Reading the file locally & NBSP; < br / >        private byte[] getBytes(String filename) throws IOException { 
        File file = new File(filename); 
        long len = file.length(); 
        lastModified = file.lastModified(); 
        byte raw[] = new byte[(int) len]; 
        FileInputStream fin = new FileInputStream(file); 
        int r = fin.read(raw); 
        if (r != len) {
            throw new IOException("Can't read all, " + r + " != " + len);
        }
        fin.close();
        return raw;
    }
}

3. The method of the thread

class Thread1 extends Thread{
  public void run(){
//Invoke the business method (to see if the file has changed)
Thread.currentThread().sleep("100000");
}

I hope this article has been helpful to your Java programming.


Related articles: