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

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

    Below is a sample snippet code to lock a file until it's process is done by JVM.

     public static void main(String[] args) throws InterruptedException {
        File file = new File(FILE_FULL_PATH_NAME);
        RandomAccessFile in = null;
        try {
            in = new RandomAccessFile(file, "rw");
            FileLock lock = in.getChannel().lock();
            try {
    
                while (in.read() != -1) {
                    System.out.println(in.readLine());
                }
            } finally {
                lock.release();
            }
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    
    }
    

提交回复
热议问题