How can I lock a file using java (if possible)

前端 未结 8 1190
无人及你
无人及你 2020-11-21 23:48

I have a Java process that opens a file using a FileReader. How can I prevent another (Java) process from opening this file, or at least notify that second process that the

8条回答
  •  北荒
    北荒 (楼主)
    2020-11-22 00:49

    Use a RandomAccessFile, get it's channel, then call lock(). The channel provided by input or output streams does not have sufficient privileges to lock properly. Be sure to call unlock() in the finally block (closing the file doesn't necessarily release the lock).

提交回复
热议问题