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

前端 未结 8 1192
无人及你
无人及你 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:44

    If you can use Java NIO (JDK 1.4 or greater), then I think you're looking for java.nio.channels.FileChannel.lock()

    FileChannel.lock()

    0 讨论(0)
  • 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).

    0 讨论(0)
提交回复
热议问题