Possible Duplicate:
Problem with Java file locking mechanism (FileLock etc)
In below code, I wanna test the FileLock
class.
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();
}
};
But the problem is that when I run "java test" twice, the first one should lock the file in.txt and the second one should not have access to in.txt, then should not print anything in screen. But the fact is the second one also print the string on the screen, even though it returns as expected. And the region from 0 to 3rd byte should not be read by others. But in fact it is not.
But there seems something wrong. If the file is locked exclusively, it cannot be accessible to others. But it seems not.