简体   繁体   中英

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

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 your intention is to know if some file was modified than you certanly don't have to retrieve last modification time. Java NIO has inotify (on Linux) wrapper called WatchService https://docs.oracle.com/javase/tutorial/essential/io/notification.html .

You can register ENTRY_MODIFY event on your file of interest and then wait till the associated watch key to be signalled.

Note that in Linux we have more granular event kinds than Java NIO provides us with. For instance ENTRY_MODIFY will be triggered when either writing or changing attributes occurred. intofiy by constast has separated type of events for that: IN_ATTRIB and IN_WRITE .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM