在java中,您可以锁定文件并检查共享访问.
您可以使用文件锁来限制从多个进程访问文件
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();
}
}
}
Run Code Online (Sandbox Code Playgroud)
您还可以通过调用来检查锁是否存在
// 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
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
3253 次 |
最近记录: |