Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I detect if a file has been modified using lastModified()

Tags:

java

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)
//.....
like image 878
user10973291 Avatar asked Dec 30 '25 03:12

user10973291


1 Answers

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 );
}
}
like image 137
Simou Avatar answered Dec 31 '25 19:12

Simou