gpt4 book ai didi

java - tryLock 功能不适用于 .text 文件

转载 作者:太空宇宙 更新时间:2023-11-04 06:35:54 24 4
gpt4 key购买 nike

如果我手动打开 .txt 文件,然后执行代码来检查文件是否打开。总是说文件未打开。但相同的代码对于任何 MS Office(.doc、.xls、.ppt)都可以按预期工作。

这是代码片段:

        File file = new File("F:\\abc.txt");
FileChannel channel = null;
FileLock lock = null;

try {

channel = new RandomAccessFile(file, "rw").getChannel();
// Get an exclusive lock on the whole file
try {
lock = channel.tryLock();
if (lock != null) {
System.out.println("Lock acquired on file: " + file.getAbsolutePath());
lock.release();
System.out.println("Lock released from closed file.");
System.out.println("Closing the channel of closed file.");
}

channel.close();
}
catch (OverlappingFileLockException | IOException e) {
// File is open by someone else
}
}
catch (FileNotFoundException e1) {
// File is open by someone else
}

每次,.txt 文件都会获取锁定,即使打开同一个文件(这与 MS Office 文件的行为不同)。

还有其他方法可以测试文件是否被其他进程打开/使用吗?

最佳答案

问题是,Windows 中的大多数程序都不会锁定文本文件。例如,如果您使用记事本打开文本文件,则可以将其删除。这意味着,notepad 不会获取锁,因此您可以在 java 程序中获取锁。

对于您的测试,您必须使用一个实际锁定文本文件的程序,或者重写您的程序,它会锁定一个文件,直到您关闭该程序。然后您可以启动您的程序两次。

关于java - tryLock 功能不适用于 .text 文件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25399310/

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