Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

[Java]How to determine whether a file is using?

Tags:

java

How to determine whether a file is using?

like image 481
Gordian Yuan Avatar asked Jan 23 '23 14:01

Gordian Yuan


1 Answers

In java you can lock Files and checking for shared access.

You can use a file lock to restrict access to a file from multiple processes

public class Locking {
   public static void main(String arsg[])
       throws IOException {
     RandomAccessFile raf =
       new RandomAccessFile("junk.dat", "rw");
     FileChannel channel = raf.getChannel();
     FileLock lock = channel.lock();
     try {
       System.out.println("Got lock!!!");
       System.out.println("Press ENTER to continue");
       System.in.read(new byte[10]);
     } finally {
       lock.release();
     }
   }
}

You also can check whether a lock exists by calling

// 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
        }
like image 168
Markus Lausberg Avatar answered Feb 05 '23 07:02

Markus Lausberg