Java I/O: Ensure a file is not locked by another process before any r/w operation

4.1k views Asked by At

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!

2

There are 2 answers

3
Peter Lawrey On

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

1
romje On

sharing documents accross processes is tricky especially when not using dedicated file systems (like GFS can be ).. I don't think that Java locking API may help you much, I think that you are on the right way with your idea of the try/fail strategy ... Using java 7 you could use a WatchService to monitor file changes and then acting as stated by your business requirements... What kind of system do you use ? Windows keeps handles on files during eternity...

HTH Jerome