0

I need to fire an event after a file change takes place while updating values in swing component. These values are stored in a file. now i need to retrieve updated value.

deepak
  • 25
  • 7
  • hi @naimdjon . i've tried to use watch service. I dnt know to create an action listener inside it. – deepak Mar 18 '14 at 13:47

1 Answers1

0

Take a look at the oficial io notification API guide for Java: http://docs.oracle.com/javase/tutorial/essential/io/notification.html

Something like that:

public class myFileWatcherBean implements ActionListener {

    private Component someComponent;

    public myFileWatcherBean() {
        someComponent.addActionListener(this);
    }

    public void watchForChanges() {
        WatchService watcher = FileSystems.getDefault().newWatchService();
        Path dir = ...;

        try {
            WatchKey key = dir.register(watcher,
                       ENTRY_CREATE,
                       ENTRY_DELETE,
                       ENTRY_MODIFY);
            key = watcher.take();
            for (WatchEvent<?> event: key.pollEvents()) {
                  actionPerformed(new ActionEvent(this, ActionEvent.ACTION_PERFORMED, null) {
      //Nothing need go here, the actionPerformed method (with the
      //above arguments) will trigger the respective listener
});
            }
        } catch (IOException x) {
            System.err.println(x);
        }

    }
}

PS: code needs some tinkering, but I think you will get the idea.

References: Can I watch for single file change with WatchService (not the whole directory)? How do I manually invoke an Action in swing? http://docs.oracle.com/javase/tutorial/essential/io/notification.html#try http://docs.oracle.com/javase/tutorial/uiswing/events/actionlistener.html

Community
  • 1
  • 1
Alexander Jardim
  • 2,406
  • 1
  • 14
  • 22
  • hi @alexander. Thanks for ur reply. i've already verified similar link. [link](http://stackoverflow.com/questions/16251273/can-i-watch-for-single-file-change-with-watchservice-not-the-whole-directory/16251508#16251508). hw could I use an action listener for this. – deepak Mar 18 '14 at 13:48