I am facing a recurring problem in an application that keeps track of the contents of files in a directory based on the Java 7 WatchService API. When the underlying file system fires a change event in a file, I want to immediately calculate its SHA-256.
But it often happens that another process has an open file (i.e. Word), thus delaying the exclusive lock and preventing my application from any read / write operation. If any stream / channel is created against an open file, FileNotFoundException or FileSystemException for the nio API is thrown with a message like:
The process cannot access the file because it is being used by another process.
I could not find a solution that would detect such cases without masking the โrealโ FileNotFoundException when the file does not actually exist in fs.
I came up with the idea of โโchecking existence through File.exists, and then if a FileNotFoundException is thrown when I open the stream, I could conclude that the file is locked. I am open to any input on this!
Thanks!
java locking nio nio2 watchservice
sylvain
source share