The example in this article describes Java's method of determining whether a file has been updated within a time period. Share it with everyone for your reference. The specific implementation method is as follows:
1. The timer copy code is as follows: private Timer timer;
/**
* Simple timer
* @param delay How long will it take to start execution. millisecond
* @param period The execution interval. millisecond
*/
public void test(long delay, long period) {
timer = new Timer();
timer.schedule(new TimerTask() {
public void run() {
//Your method of operation
System.out.println(System.currentTimeMillis());
}
}, delay, period);
}
2. The deepened version of the copy code is as follows: package classloader;
/**
* @author vma
*/
// Customize a class loader
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 modified, load it. If it has not been modified, return the current
public Class loadClass(String name) throws ClassNotFoundException, IOException{
if (isClassModified(name)){
dc = new DynamicClassLoader();
return c = dc.findClass(getBytes(name));
}
return c;
}
//Determine whether it has been modified
private boolean isClassModified(String filename) {
boolean returnValue = false;
File file = new File(filename);
if (file.lastModified() > lastModified) {
returnValue = true;
}
return returnValue;
}
//Read file from local
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 thread method copy code is as follows: class Thread1 extends Thread{
public void run(){
//Call business method (check whether the file has changed)
Thread.currentThread().sleep("100000");
}
I hope this article will be helpful to everyone’s Java programming.