Java I / O: make sure the file is not locked by another process before any r / w operation

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!

+8
java locking nio nio2 watchservice
source share
2 answers

Did you try to lock the file yourself? I assume that you can only get a lock if it is not locked and does not exist.

http://docs.oracle.com/javase/7/docs/api/java/nio/channels/FileChannel.html#tryLock%28%29

+1
source share

exchange of documents by processes is difficult, especially if you do not use dedicated file systems (for example, GFS). I donโ€™t think the Java blocking API can really help you, I think that you are on the right track with the idea of โ€‹โ€‹a try / fail strategy ... Using java 7, you can use WatchService to monitor file changes and then act as indicated in your business requirements ... What system are you using? Windows has been storing files in files for ages ...

NTN Jerome

0
source share

All Articles