Aneesh
Aneesh

Reputation: 1733

Event for change in text file content

My java program needs to know if a text file content changes. Currently Im using File.lastModified() method to do it but ideally I don't want to perform the check. Instead I want an event to fire every time the file is modified. Are there any third party libraries available for this kind of thing? I've heard it can be accomplished using apache file descriptors but couldn't find any information regarding it.

Upvotes: 1

Views: 305

Answers (4)

MrSimpleMind
MrSimpleMind

Reputation: 8597

There are many factors that might determine your solution. How often the files updates, what type the information is, etc...

My advice would be either the Java 7 standard, or the Apache de facto standard (if the requirement wont allow Java 7 solution)...


Apache configuration

If it is a file that is kind of property information, a configuration, then you might want to look at Apache commons configuration. Which gives a refresh method each time the file is updated, to reload your configuration, etc. http://commons.apache.org/proper/commons-configuration/userguide/howto_events.html#An_example


Java 7, WatchService

If you use Java 7, look at the WatchService, link http://docs.oracle.com/javase/7/docs/api/java/nio/file/WatchService.html


Apache IO

If you dont want to use Java 7, and the file is not a configuration (which is better to use commons configuration that way), then you might want to look at FileAlterationObserver from Apache io. http://commons.apache.org/proper/commons-io/

Upvotes: 2

GreenGodot
GreenGodot

Reputation: 6753

Try Apache's DefaultFileMonitor.

All you need to do is add the file in question to the list of files that need to be monitored and start the monitoring thread.

If the file has been changed or deleted it shall fire an OnChange event.

Upvotes: 1

SpongeBobFan
SpongeBobFan

Reputation: 964

Google say that you can use libraries like JNotify and inotify-java

Upvotes: 0

Will
Will

Reputation: 6711

You can accomplish this with the new Java 7 WatchService. This enables you to watch a directory and be notified of create, modified and delete events.

Upvotes: 2

Related Questions