I know I can use lastModified() to get the last modified time of a file. What I don't understand is that how can I use this method to detect if a file has been changed or not. Do I compare it with the current time? I was trying to do the following but I don't think it works
long time = xx.lastModified();
if(time != localtime)
//.....
for this problem there are so many solutions, i know this one: For a single file, a thread is launched to check the lastModified value and compare it with the previous value.
import java.util.*;
import java.io.*;
public abstract class FileWatcher extends TimerTask {
private long timeStamp;
private File file;
public FileWatcher( File file ) {
this.file = file;
this.timeStamp = file.lastModified();
}
public final void run() {
long timeStamp = file.lastModified();
if( this.timeStamp != timeStamp ) {
this.timeStamp = timeStamp;
onChange(file);
}
}
protected abstract void onChange( File file );
}
here is the main for the test:
import java.util.*;
import java.io.*;
public class FileWatcherTest {
public static void main(String args[]) {
// monitor a single file
TimerTask task = new FileWatcher( new File("c:/temp/text.txt") ) {
protected void onChange( File file ) {
// here we code the action on a change
System.out.println( "File "+ file.getName() +" have change !" );
}
};
Timer timer = new Timer();
// repeat the check every second
timer.schedule( task , new Date(), 1000 );
}
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With