目录
一、ByteBuffer 正确使用的步骤
- 一、ByteBuffer 正确使用的步骤
- 二、ByteBuffer的基本使用示例
- 1.1、pom.xml文件引入依赖
- 1.2、创建test.txt文件
- 1.3、示例代码
- 1.4、输出结果
- 向 buffer 写入数据,例如:调用 channel.read(buffer)
- 调用 flip() 切换至读模式,例如:调用buffer.flip()
- 从 buffer 读取数据,例如:调用 buffer.get()
- 调用 clear() 或 compact() 切换至写模式,例如:调用buffer.clear()或 buffer.compact()
- 重复 1~4 步骤。
io.netty
netty-all
4.1.39.Final
org.projectlombok
lombok
1.16.18
com.google.code.gson
gson
2.8.5
com.google.guava
guava
19.0
ch.qos.logback
logback-classic
1.2.3
com.google.protobuf
protobuf-java
3.11.3
1.2、创建test.txt文件
package com.example.nettytest.nio.day1;
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @description:
* @author: xz
* @create: 2022-07-18 22:17
*/
@Slf4j
public class TestByteBuffer {
public static void main(String[] args) {
//FileChannel
try (FileChannel channel = new FileInputStream("test.txt").getChannel()) {
//allocate:分配一个新的字节缓冲区,容量为10
ByteBuffer buffer = ByteBuffer.allocate(10);
while(true){
// 从 channel 读取数据,向 buffer 写入
int len = channel.read(buffer);
log.info("读取到的字节数 {}", len);
if(len ==-1){
break;
}
// 打印 buffer 的内容
buffer.flip();// 切换至读模式
while (buffer.hasRemaining()){// 是否还有剩余未读数据
byte b = buffer.get();
log.info("实际字节 {}", (char) b);
}
buffer.clear(); // 切换为写模式
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
1.4、输出结果