I'm encountering a recurrent issue in an application that tracks content of files within a directory, based on the Java 7 WatchService API. When the underlying file system fires a modification event on a file, I want to compute its SHA-256 right away.
But it often occurs that another process has the file opened (i.e. Word), thus detaining an exclusive lock and preventing my app from any read/write operation. If any Stream/Channel is created against the opened file, a FileNotFoundException or a FileSystemException for nio API's is thrown with a message like :
The process cannot access the file because it is being used by another process
I wasn't able to come with a solution that would detect such cases without masking a "real" FileNotFoundException when the file does not actually exists on the fs.
I've come up with the idea to check existence via File.exists and then if a FileNotFoundException is thrown when I open a stream I would be able to infer that the file is locked. I am open to any input on this!
Thanks!
Have you tried locking the file yourself? I would assume you can only acquire a lock if its not locked and exists.
http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#tryLock%28%29