【发布时间】:2014-12-07 03:04:15
【问题描述】:
可能重复:
Problem with Java file locking mechanism (FileLock etc)
在下面的代码中,我想测试FileLock 类。
import java.io.File;
import java.nio.channels.*;
import java.nio.MappedByteBuffer;
import java.io.RandomAccessFile;
class test{
File f= new File("./in.txt");
RandomAccessFile in = new RandomAccessFile(f, "rw");
FileChannel fc = in.getChannel();
byte[] t = new byte[20];
in.read(t, 0, 8);
System.out.println(new String(t));
FileLock fl = fc.tryLock(0, 4, false);
if(fl!=null){
System.out.println("the file has been locked");
Thread.sleep(10000);
fl.release();
System.out.println("no lock!");
}
fc.close();
in.close();
}
};
但问题是,当我运行“java test”两次时,第一个应该锁定文件 in.txt,第二个不应该访问 in.txt,然后不应该在屏幕上打印任何内容。但事实是第二个也在屏幕上打印字符串,即使它按预期返回。并且从 0 到第 3 个字节的区域不应该被其他人读取。但事实上并非如此。
但似乎有些不对劲。如果文件被独占锁定,则其他人无法访问它。但好像没有。
【问题讨论】:
-
好吧,我收到了这个
java.io.IOException: The process cannot access the file because another process has locked a portion of the file,所以它阻止了这里的阅读。 -
真的吗?你如何运行它?我打开两个终端,分别在Ubuntu下运行
-
它适用于其他所有人。在这两种情况下,您是否从同一目录运行它?
-
请看这个帖子的答案:stackoverflow.com/questions/2479222/…
-
文件锁是平台提供的,不是Java提供的。锁按规定工作。因此,不是错误。
标签: java