FileChannel 类为 Java 提供对于文件锁定的稳固支持。您可以锁定文件或文件区域,甚至可以锁定不存在的文件区域。锁定可以被共享或独占(我会对其差别作一些解释)并可以通过阻塞或轮询而获得。FileChannel 类提供获取锁定的四种不同方法:
public class FileChannel ... {
// Block to get a lock
FileLock lock();        // nonshared
FileLock lock(long position, long size, boolean shared);// Try to get a lock, or null if not available
FileLock tryLock();
FileLock tryLock(long position, long size, boolean shared);
}以下的代码是对文件进行独占的追加: 
// Get a channel, the size, and a lock
FileChannel ch =
new FileOutputStream("/tmp/log",
true).getChannel();
long size = ch.size();
FileLock lock =
ch.lock(size, Long.MAX_VALUE-size, false);try {
ch.write(buf);
}
finally {
lock.release();
ch.close(); // this would have done a release
}