2. ByteBuffer

简介: 2. ByteBuffer

image.png

@Slf4j
public class ChannelDemo1 {
public static void main(String[] args) {
try (RandomAccessFile file = new RandomAccessFile("helloword/data.txt", "rw")) {
FileChannel channel = file.getChannel();
ByteBuffer buffer = ByteBuffer.allocate(10);
do {
// 向 buffer 写入
int len = channel.read(buffer);
log.debug("读到字节数:{}", len);
if (len == -1) {
break;
}
// 切换 buffer 读模式
buffer.flip();
while(buffer.hasRemaining()) {
log.debug("{}", (char)buffer.get());
}
// 切换 buffer 写模式
buffer.clear();
} while (true);
} catch (IOException e) {
e.printStackTrace();
}
}
}
作者:用户5488193880519
链接:https://juejin.cn/post/7282588016270606388
来源:稀土掘金
著作权归作者所有。商业转载请联系作者获得授权,非商业转载请注明出处。
目录
相关文章
|
8月前
2.1 ByteBuffer 正确使用姿势
2.1 ByteBuffer 正确使用姿势
38 0
|
8月前
|
索引
2.3 ByteBuffer 常见方法
2.3 ByteBuffer 常见方法
31 0
|
8月前
|
存储
ByteBuffer 大小分配
ByteBuffer 大小分配
53 0
|
10月前
|
存储 Java
NIO之Buffer解读(下)
NIO之Buffer解读(下)
|
10月前
|
存储 Java 容器
|
12月前
|
算法 Java 索引
ByteBuffer
ByteBuffer
51 0
|
存储 消息中间件 缓存
ByteBuffer总结
ByteBuffer总结
|
Java
|
Java 测试技术 容器
NIO 下的 ByteBuffer简单学习
NIO 下的 ByteBuffer简单学习
99 0
NIO学习二-ByteBuffer
前面我们已经了解到Buffer中,0<=mark<=postion<=limit<=capacity。其中mark是标记,如果为-1时丢弃。postion是当前位置,limit是限制,也即上界。capacity是容量。同时了解了直接缓冲区与缓冲区的底层实现是不同的,缓冲区是基于数组的,而直接缓冲区是基于内存的。同时可以基于反射,拿到cleaner,进而拿到clean进行清理。同时clear是还原缓冲区的状态,flip是反转缓冲区的,rewind重绕缓冲区,标记清除。remianing对剩余元素的个数记录。offset获取偏移量。 ByteBuffer是Buffer的子类,可以在缓冲区以字节为单
81 0
NIO学习二-ByteBuffer