我想在同一个锁下执行读取和写入。获取锁后,我想读取文件,进行一些数据操作,然后将该数据写入同一个文件。
我尝试过以下方法:
val storeChannel =
FileChannel.open(
target,
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.CREATE
)
return runLocking(storeChannel) { channel ->
val inStream = Channels.newInputStream(channel)
val store = inStream.use { serializer.read(it) }
val result = operation(store)
val outStream = Channels.newOutputStream(channel)
outStream.use { serializer.write(it, store) }
result
}
(
runLocking
函数只是获取给定通道的锁,运行大括号中的代码,然后解锁)
但是,通道在读取后会关闭,因此无法写入。我在网上读到可以使用
RandomAccessFile
来实现这一点,但我不想 mmap
整个文件(这就是我假设 RandomAccessFile
所做的),因为我的写入始终是连续的。
有没有办法获取一个锁来同时进行读和写?或者
RandomAccessFile
是我唯一的选择?
对于锁定,您不应该使用
FileChannel.lock
吗?类似的东西
fun openLocked(target: Path): FileChannel =
FileChannel.open(
target,
StandardOpenOption.READ,
StandardOpenOption.WRITE,
StandardOpenOption.CREATE
).also { it.lock() }
看看这个玩具示例是否适合您(我相信代码中派生流上的
use
会关闭通道)
val fc = openLocked( somePath )
fc.use { stream ->
val ins = Channels.newInputStream(stream)
val store = String(ins.readBytes())
val os = Channels.newOutputStream(stream)
os.write("$store !!!".toByteArray())
}