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

前端 未结 8 1198
无人及你
无人及你 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条回答
  •  梦毁少年i
    2020-11-22 00:43

    Don't use the classes in thejava.io package, instead use the java.nio package . The latter has a FileLock class. You can apply a lock to a FileChannel.

     try {
            // Get a file channel for the file
            File file = new File("filename");
            FileChannel channel = new RandomAccessFile(file, "rw").getChannel();
    
            // Use the file channel to create a lock on the file.
            // This method blocks until it can retrieve the lock.
            FileLock lock = channel.lock();
    
            /*
               use channel.lock OR channel.tryLock();
            */
    
            // Try acquiring the lock without blocking. This method returns
            // null or throws an exception if the file is already locked.
            try {
                lock = channel.tryLock();
            } catch (OverlappingFileLockException e) {
                // File is already locked in this thread or virtual machine
            }
    
            // Release the lock - if it is not null!
            if( lock != null ) {
                lock.release();
            }
    
            // Close the file
            channel.close();
        } catch (Exception e) {
        }
    

提交回复
热议问题