gpt4 book ai didi

java - 打开 FileDescriptor 以使用 Channel 进行读写

转载 作者:太空宇宙 更新时间:2023-11-04 12:23:44 27 4
gpt4 key购买 nike

我有一个FileDescriptor并且想打开它以使用单个 channel 进行读写。我可以使用像这样的流来获取一个用于读取的 channel 和一个用于写入的 channel ,但我更喜欢单个 channel 。

FileChannel in = new FileInputStream(fd).getChannel();
FileChannel out = new FileOutputStream(fd).getChannel();

最佳答案

最近一直在使用FileChannel,是的,只要您使用不修改 channel 位置的方法,您就可以使用1个FileChannel进行读写。事实上,这是您获得一致的文件 View 的唯一方法,因为至少在刷新之前,写入操作可能会被操作系统分页/缓存,而其他读取器尚未“可见”。这是摘自 Javadoc

File channels are safe for use by multiple concurrent threads. The close method may be invoked at any time, as specified by the Channel interface. Only one operation that involves the channel's position or can change its file's size may be in progress at any given time; attempts to initiate a second such operation while the first is still in progress will block until the first operation completes. Other operations, in particular those that take an explicit position, may proceed concurrently; whether they in fact do so is dependent upon the underlying implementation and is therefore unspecified.

我使用单线程写入(改变位置)和多线程读取(不改变位置,即读取(ByteBuffer dst,长位置))

干杯

关于java - 打开 FileDescriptor 以使用 Channel 进行读写,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38581024/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com