• Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

File Monitoring Service in Java 7

 
Hardy Shah
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello All,

I am working on a software which monitors any modification in file and based on that performs some business logic. To implement the same, I am using Watch Service in Java 7 (http://docs.oracle.com/javase/tutorial/essential/io/notification.html ). However, using the code mentioned in above link, my software always receive File- Modification events, even when I am just saving the file, there is nothing changed in the file.

Ideally, my software should receive Modification events only when file is actually changed, not every time some-one just save the file. I also tried with JNotify-API and results where the same.

Any help or suggestions for the same is appreciated


Regards,
Hardik Shah
 
Mike Simmons
Ranch Hand
Posts: 3040
10
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Yeah, unfortunately we don't really have any way of knowing whether something was changed or not during a save, without examining the file contents. That info simply isn't provided. If it was me, I would probably create a Map or DB table of file paths and their file lengths and some hash of the file. If the length changes, you know there's a change; otherwise you still need to examine bytes to see if the content changed. I would calculate a new hash of the content and see if that hash changed - if it did, you definitely have a file change. If the hash didn't change, then you probably don't have any file change. But you can't be completely sure without doing a byte-by-byte comparison.
 
Hardy Shah
Greenhorn
Posts: 4
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Hello Mike,

Thanks for the Reply and Suggestions.

I tried the same sample in Mac-OS, and it works fine. The software only receives events when file is actually changed. It seems that it depends upon underlying platform.


Regards,
Hardik Shah

 
Tim Holloway
Saloon Keeper
Pie
Posts: 18098
50
Android Eclipse IDE Linux
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Saving a file normally changes its modification date, even if the data itself is unchanged. So by that metric, the file has "changed".

If you want to verify that a file's contents are unchanged, the typical approach is to take a checksum (usually MD5) of the original file and compare it with the checksum of the file after you got the change notification. That process can be speeded up by first checking metadata such as the file's length, since obviously a change in length indicates a change in content and that way you have an instant answer without the work of computing the new checksum.
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic