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

标签 java

我有一个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/

相关文章:

java - 使用不同 SC 系列的智能卡探测 : command to clean the SC state

java - 如果用户输入不是数字(0-9)或算术运算符(+ - */),如何使 JOptionPane 显示错误

java - 自定义连接池慢(JAVA)?

java - 更新 firebase 和 Google 服务依赖项后无法构建项目

java.util.ConcurrentModificationException 但我没有删除

java - 使用 JNI 创建一个简单的 dll 文件

java - 我们如何将与java中的对象关联的所有引用设置为null?

java - Spring Boot 审核主机名和 HostIp

Java多线程和迭代器,应该很简单,初学者

java - 为什么我需要在此 Java 示例中强制转换 HttpURLConnection?