Java FileLock for Reading and Writing
- Are you aware that locking the file won't keep other processes from touching it unless they also use locks?
- You have to lock via a writable channel. Get the lock via a
RandomAccessFile
in "rw" mode and then open yourFileInputStream
. Make sure to close both!
It would be better if you created the lock using tryLock(0L, Long.MAX_VALUE, true)
.
This creates a shared lock which is the right thing to do for reading.
tryLock()
is a shorthand for tryLock(0L, Long.MAX_VALUE, false)
, i.e. it requests an exclusive write-lock.