Question

I am trying to monitor a text file for a change in the one line of text it contains. The file is constantly being deleted and created with the same name and path but the content rarely changes.

I am trying to construct an if statement so that if the content of the file changes then the system will print to the console.

I have looked at this Stack Overflow question and tried using the java-diff-utils example found on this page, but I could not find a way to implement it to solve my problem.

Was it helpful?

Solution

Start by generating an MD5 of the original file, then using a background Thread, recalculate the MD5 and compare it with the original. When the hash changes, the file contents would have changed.

Check out MD5 Hashing Example

If you're using Java 7, you could use the Watcher Service to monitor changes to the file. This would replace the thread

OTHER TIPS

"High-level" advice: you could...

  • Consume the file contents in a custom Object at app initialization, and store it in a static variable
  • Define a property for said object, returning a String which represents the contents of the file
  • Use a TimerTask to periodically instantiate a new instance of said custom Object representing the file, and...
  • ... compare the two String properties, so that you can print out the latter should they not be equal, and then overwrite the static variable's value with the newly instantiated object

Note that this is hardly the professional way to handle recurrent tasks or file comparison - it's just meant to give you a draft direction.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top