gpt4 book ai didi

java - 尝试锁定文件进行读取时感到失望

转载 作者:行者123 更新时间:2023-12-01 13:14:40 26 4
gpt4 key购买 nike

我试图让每个线程读取自己的文本文件。

   private void burden() {

File mainFolder = new File("C:\\FilesToRead");
File[] files = mainFolder.listFiles();
String freeFile;

for (File file : files) {

FileChannel channel;
FileLock lock = null;
try {
channel = new RandomAccessFile(file, "r").getChannel();;
lock = channel.lock();
// Ok. We get the lock
readFile(file.getName());

} catch (OverlappingFileLockException e) {
continue; // File is open by someone else
} catch (FileNotFoundException f) {

} catch (IOException ex) {

} catch (NonWritableChannelException n) {
System.out.println("NonWritableChannelException");
} finally {
try {
lock.release();
} catch (IOException ex) {
System.out.println("IOException!");
}
}

}
} // burden();

我在调试器中得到这张图片:

enter image description here

下一步将把我带到 NonWritableChannelException。

我不明白为什么,因为我试图锁定文件以供读取。

最佳答案

javadoc给出了答案。您使用 .lock(),相当于调用 .lock(0L, Long.MAX_VALUE, false)

第三个参数,一个 boolean 值,被描述为(强调我的):

true to request a shared lock, in which case this channel must be open for reading (and possibly writing); false to request an exclusive lock, in which case this channel must be open for writing (and possibly reading)

您必须.lock(0L, Long.MAX_VALUE, true)

<小时/>

此外,如果您使用的是 Java 7,请使用 FileChannel.open()

关于java - 尝试锁定文件进行读取时感到失望,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22569551/

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