I want to write something at the end of the file every time the file is modified, and I use this 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) {
and stream 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) { for (WatchEvent event : key.pollEvents()) {
I want to get something like in the file:
acasc 0dong dwqcacesv 1dong terert 2dong
However, now I get this because it writes too many times in the file:
acasc 0dong 1dong ... 50123dong
If I use System.out.println(counter); , it works the way I want (it correctly prints the number of file changes), but it is wild on fw.write(counter + content);
source share