Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

WatchService / Deletions / File or Directory?

Tags:

java

java-7

I want to detect if a file or directory has been deleted. Obviously I can't use Files.isDirectory(Path) and the equivalent for files, because the file/directory is already deleted.

I thought about using two WatchService instances to watch either for file changes or for directory changes, then I know all the time if it's a file or directory. Sadly I can't find an appropriate method.

Edit: I think any other solution regarding the checking of a String representation of filenames vs. directories is error prone.

like image 549
Johannes Avatar asked Nov 20 '11 14:11

Johannes


1 Answers

Keep a local copy of the metadata in the directory you're watching - from simply just a list of entries along with whether each is a file or directory, along with any other attributes you may be interested in once deleted - e.g. size or last modified time. You can then consult this metadata once you receive a delete notification.

You could populate this metadata store when you start your watch loop - and extend your watcher with ENTRY_CREATE and ENTRY_MODIFY to keep your metadata store up-to-date as other changes are made while the directory is being watched.

Granted, this won't be without some additional overhead in memory to hold on to this data, but for most use cases, it should be rather insignificant.

like image 102
ziesemer Avatar answered Nov 20 '22 18:11

ziesemer