How to write only once to a file from a stream?

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) { // TODO Auto-generated catch block e.printStackTrace(); } catch (InterruptedException e) { // TODO Auto-generated catch block e.printStackTrace(); } } } 

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()) { //System.out.printf("Received %s event for 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 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);

+6
source share
1 answer

Your stream entry causes further changes to the file. Nutritious loop.

0
source

Source: https://habr.com/ru/post/988865/


All Articles