简体   繁体   中英

WatchService / Deletions / File or Directory?

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.

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 - eg 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM