锁定
可以使用 FileChannel
API 锁定文件,该输出可以从输入输出 streams
和 readers
获取
streams
的例子
//打开文件流 FileInputStream ios = new FileInputStream(filename);
// get underlying channel
FileChannel channel = ios.getChannel();
/*
* try to lock the file. true means whether the lock is shared or not i.e. multiple processes can acquire a
* shared lock (for reading only) Using false with readable channel only will generate an exception. You should
* use a writable channel (taken from FileOutputStream) when using false. tryLock will always return immediately
*/
FileLock lock = channel.tryLock(0, Long.MAX_VALUE, true);
if (lock == null) {
System.out.println("Unable to acquire lock");
} else {
System.out.println("Lock acquired successfully");
}
// you can also use blocking call which will block until a lock is acquired.
channel.lock();
// Once you have completed desired operations of file. release the lock
if (lock != null) {
lock.release();
}
// close the file stream afterwards
// Example with reader
RandomAccessFile randomAccessFile = new RandomAccessFile(filename, "rw");
FileChannel channel = randomAccessFile.getChannel();
//repeat the same steps as above but now you can use shared as true or false as the channel is in read write mode