2

Is there a way to somehow trigger an event that will do something every time a file change? I mean something like that (in pseudo code)

if(DetectedFileModified(pathToFile)){ do stuff }

I know I can do it periodically but can I somehow do it without a timer? I want to be able to make some actions when a user is updating a txt file (not via code, but just by opening the file and writing inside) and I don't know when he'll do it.

CodeMonkey
  • 11,196
  • 30
  • 112
  • 203
  • 1
    http://docs.oracle.com/javase/tutorial/essential/io/notification.html – SLaks Aug 14 '13 at 20:48
  • What is your environment (e.g. Standalone, Application-Server, Eclipse-IDE, ...) – t777 Aug 14 '13 at 21:12
  • possible duplicate of [Can I watch for single file change with WatchService (not the whole directory)?](http://stackoverflow.com/questions/16251273/can-i-watch-for-single-file-change-with-watchservice-not-the-whole-directory) – Boris the Spider Aug 14 '13 at 21:43

1 Answers1

7

You need a WatchService

The WatchService API is fairly low level, allowing you to customize it. You can use it as is, or you can choose to create a high-level API on top of this mechanism so that it is suited to your particular needs.

Oracle blog on the same

Suresh Atta
  • 120,458
  • 37
  • 198
  • 307