java - How to write only once to file from a thread? -
i want write end of file every time file modified , i'm using code :
public class main { public static final string directory_to_watch = "d:\\test"; public static void main(string[] args) { path towatch = paths.get(directory_to_watch); if (towatch == null) { throw new unsupportedoperationexception(); } try { watchservice mywatcher = towatch.getfilesystem().newwatchservice(); filewatcher filewatcher = new filewatcher(mywatcher); thread t = new thread(filewatcher, "filewatcher"); t.start(); towatch.register(mywatcher, standardwatcheventkinds.entry_modify); t.join(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
and thread class :
public class filewatcher implements runnable{ private watchservice mywatcher; private path towatch; string content = "dong\n"; int counter = 0; public filewatcher (watchservice mywatcher, path towatch) { this.mywatcher = mywatcher; this.towatch = towatch; } @override public void run() { try { watchkey key = mywatcher.take(); while (key != null) { (watchevent event : key.pollevents()) { //system.out.printf("received %s event file: %s\n", event.kind(), event.context()); //system.out.println(counter); mywatcher = null; file file = new file(main.directory_to_watch + "\\" + event.context()); filewriter fw = new filewriter(file.getabsolutefile(), true); fw.write(counter + content); fw.close(); counter++; mywatcher = towatch.getfilesystem().newwatchservice(); towatch.register(mywatcher, standardwatcheventkinds.entry_modify); // bufferedwriter bwwriter = new bufferedwriter(fw); // bwwriter.write(content); // bwwriter.close(); } key.reset(); key = mywatcher.take(); } } catch (interruptedexception e) { // todo auto-generated catch block e.printstacktrace(); } catch (ioexception e) { // todo auto-generated catch block e.printstacktrace(); } } }
i want in file :
acasc 0dong dwqcacesv 1dong terert 2dong
however, i'm getting this, because writes many times in file:
acasc 0dong 1dong ... 50123dong
if use system.out.println(counter);
works want (prints number of file changes correctly), goes wild on fw.write(counter + content);
your thread's write causing further changes file. self feeding loop.
Comments
Post a Comment