detect file changes in Java without WatchService -
i created file checker checks file changes every x sec. problem if check file watchservice send modify event if touch file
. can check file.lenght
, if changes not change file size? there idea how can detect file changes?
this code( i'm using lastmodified()
method while )
class checker implements runnable { static logger log = logger.getlogger(monitor.class.getname()); private static final long default_check_interval = 5000; //5 sec private static simpledateformat dataformat = new simpledateformat("mm/dd/yyyy hh:mm:ss"); private file file; private long checkinterval; public checker(string path, long checkinterval) throws exception { this.file = new file(path); this.checkinterval = checkinterval > 1000 ? checkinterval : default_check_interval; } private jsonobject loadconfig() { jsonobject conf = null; try(bufferedreader reader = new bufferedreader(new filereader(this.file));) { stringbuilder bldr = new stringbuilder((int) this.file.length()); string line = null; while((line = reader.readline()) != null) { bldr.append(line); } conf = new jsonobject(bldr.tostring()); thread.sleep(this.checkinterval); } catch (exception e) { log.error(e); } return conf; } @override public void run() { long moddate = 0; while (true) { long lastmodified = this.file.lastmodified(); jsonobject conf = loadconfig(); if (lastmodified != moddate) { moddate = lastmodified; log.warn("file changed @ " + dataformat.format(lastmodified)); log.info(conf.get("name") + ", " + conf.get("company")); } log.info("no chenges"); } }
public class monitor { public static void main(string[] args) throws exception { new thread(new checker("/home/arno/test/config.json", 2000)).start(); } }
maintain duplicate of file in other directory.
for instance have file on desktop
, maintain copy of file in c:
, check difference.
file source = new file(""c://desktop//filename.txt"); file dest = new file("c://temp//cache-filename.txt"); try { fileutils.copydirectory(source, dest); } catch (ioexception e) { e.printstacktrace(); }
and maintain timer, call everytime.
timer timer = new timer(); timer.scheduleatfixedrate(new timertask() { @override public void run() { if(comapretwofiles("c://temp//cache-filename.txt", "c://desktop//filename.txt")){ system.out.println("file changed"); //change cache file } } }, 2*60*1000, 2*60*1000); public boolean comparetwofiles(string path1, string path2) throws ioexception { file file1 = new file(path1); file file2 = new file(path2); bufferedreader br1 = new bufferedreader(new filereader(file1)); bufferedreader br2 = new bufferedreader(new filereader(file2)); string thisline = null; string thatline = null; list<string> list1 = new arraylist<string>(); list<string> list2 = new arraylist<string>(); while ((thisline = br1.readline()) != null) { list1.add(thisline); } while ((thatline = br2.readline()) != null) { list2.add(thatline); } br1.close(); br2.close(); return list1.equals(list2); }
Comments
Post a Comment