gpt4 book ai didi

java - [Java]如何判断一个文件是否正在使用?

转载 作者:搜寻专家 更新时间:2023-11-01 01:39:22 24 4
gpt4 key购买 nike

如何判断一个文件是否被使用?

最佳答案

在 java 中,您可以锁定文件并检查 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();
}
}
}

您还可以通过调用检查是否存在锁

// 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
}

关于java - [Java]如何判断一个文件是否正在使用?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/886315/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com