CodeMonkey
CodeMonkey

Reputation: 12444

Java how to detect file changes

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.

Upvotes: 2

Views: 5798

Answers (1)

Suresh Atta
Suresh Atta

Reputation: 122016

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

Upvotes: 8

Related Questions