Once every second, you can determine whether a file in a specified directory has been modified. If the file is modified, "file changed…" is printed on the console ..."
In this case, the lastmodified () method of the file class is called to obtain the last modification time of the file;
Thread's sleep (1000) method enables the thread to sleep for 1 second.
Java code
- Import java. Io. file;
- Import java. util. date;
- /**
- * @ Author $ kangmiao $
- * 1. check whether a specified file is modified once every second. If it is modified,
- * "File changed…" is printed on the console ..." And last modification time
- */
- Public class judgechanged {
- Private string infile;
- Boolean flag = true;
- Public judgechanged (string infile ){
- Super ();
- This. infile = infile;
- }
- Public void run (){
- File file = new file (infile );
- While (FLAG) {// always monitor
- Try {
- Long S1 = file. lastmodified ();
- Thread. Sleep (1000 );
- Long S2 = file. lastmodified ();
- Date date2 = new date (S2 );
- If (S1! = S2) {// determine whether the last modification time before and after one second is equal
- System. Out. println ("file changed -------");
- System. Out. println ("modified at:" + date2 );
- }
- } Catch (interruptedexception e ){
- E. printstacktrace ();
- }
- }
- }
- Public static void main (string [] ARGs ){
- Judgechanged JC = new judgechanged ("E:/peixun/tet.txt ");
- System. Out. println ("is the listening File Modified ·······");
- JC. Run ();
- }
- }
From: http://miaoge.iteye.com/blog/774233