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

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

    FileChannel.lock is probably what you want.

    try (
        FileInputStream in = new FileInputStream(file);
        java.nio.channels.FileLock lock = in.getChannel().lock();
        Reader reader = new InputStreamReader(in, charset)
    ) {
        ...
    }
    

    (Disclaimer: Code not compiled and certainly not tested.)

    Note the section entitled "platform dependencies" in the API doc for FileLock.

提交回复
热议问题