01、Netty学习笔记—(三大组件、bytebuffer、文件编程)(上)
@[toc]
netty笔记汇总:Netty学习指南(资料、文章汇总)
根据黑马程序员netty视频教程学习所做笔记,部分内容图例来源黑马笔记
笔记demo案例仓库地址: Github-【netty-learn】、Gitee-【netty-learn】
一、三大组件
1.1、Channel & Buffer
Channel
:数据的传输通道,双向通道,即可输入也可以输出
Buffer
:输入数据需要临时存储在内存中,它就是一个内存缓冲区,暂存channel读入的数据,同样写出数据也是需要先写到buffer,应用程序与网络之间的桥梁,用于暂存数据的缓冲区。
Stream
:以前的输入输出流也是数据的传输通道。
channel 有一点类似于 stream,它就是读写数据的双向通道,可以从 channel 将数据读入 buffer,也可以将 buffer 的数据写入 channel,而之前的 stream 要么是输入,要么是输出,channel 比 stream 更为底层
常见的 Channel 有
- FileChannel:文件的数据传输通道
- DatagramChannel:UDP网络传输通道
- SocketChannel:TCP数据传输通道,客户端/服务端都OK
- ServerSocketChannel:TCP,专用服务端
buffer 则用来缓冲读写数据,常见的 buffer 有
- ByteBuffer(最常用):以字节为单位缓冲数据。下面是实现类
- MappedByteBuffer
- DirectByteBuffer
- HeapByteBuffer
- 不同数据类型:
- ShortBuffer
- IntBuffer
- LongBuffer
- FloatBuffer
- DoubleBuffer
- CharBuffer
1.2、Selector
selector 单从字面意思不好理解,需要结合服务器的设计演化来理解它的用途
多线程版设计
- windows下一个线程就有1MB,若是连接不断增加,内存就会不足,可能产生OOM。
缺点:
- 内存占用高
- 线程上下文切换成本高
- 只适合连接数少的场景
线程多了CPU也要跟的上才行,若是你的电脑是16核,那么在同一时间跑的也只有16个线程,更多的线程只能等待,那么其他线程的状态信息都需要进行临时保存。(如执行函数、存储变量)
线程池版设计
早期的Tomcat
就采用了这个线程池版设计
缺点:
- 阻塞模式下,线程仅能处理一个 socket 连接
- 仅适合短连接场景:来了一个连接之后快速处理好业务直接就断开连接,好让线程池中的线程去处理其他事情。一般都是为http请求
selector 版设计
selector 的作用就是配合一个线程来管理多个 channel,获取这些 channel 上发生的事件,这些 channel 工作在非阻塞模式下,不会让线程吊死在一个 channel 上。适合连接数特别多,但流量低的场景(low traffic)
- 解释:在这里thread是服务员,channel是客人,而selector则是能够检测到所有客户需求的工具,对应channel的一举一动都在监视之中,一旦某个channel进行了请求,那么selector就会执行,紧接着selector就会去通知线程thread来对channel进行处理
- 问题(为什么适合流量低的原因,若是流量高呢?):若是某个连接不断的发送请求数据,那么就会造成一个问题就是线程会一直处理该channel的事件,那么其他事件都会一直在等待中。
调用 selector 的 select() 会阻塞直到 channel 发生了读写就绪事件,这些事件发生,select 方法就会返回这些事件交给 thread 来处理
二、ByteBuffer
ByteBuffer初应用
目标:使用channel以及bytebuffer来读取当前项目路径下的文件内容。
技术:channel+bytebuffer API、logback+lombok
<dependency>
<groupId>io.netty</groupId>
<artifactId>netty-all</artifactId>
<version>4.1.32.Final</version>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.20</version>
</dependency>
resources/loback.xml
:用于指定日志的输出
<?xml version="1.0" encoding="UTF-8"?>
<configuration
xmlns="http://ch.qos.logback/xml/ns/logback"
xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://ch.qos.logback/xml/ns/logback logback.xsd">
<!-- 输出控制,格式控制-->
<appender name="STDOUT" class="ch.qos.logback.core.ConsoleAppender">
<encoder>
<pattern>%date{HH:mm:ss} [%-5level] [%thread] %logger{17} - %m%n </pattern>
</encoder>
</appender>
<!--<appender name="FILE" class="ch.qos.logback.core.rolling.RollingFileAppender">
<!– 日志文件名称 –>
<file>logFile.log</file>
<rollingPolicy class="ch.qos.logback.core.rolling.TimeBasedRollingPolicy">
<!– 每天产生一个新的日志文件 –>
<fileNamePattern>logFile.%d{yyyy-MM-dd}.log</fileNamePattern>
<!– 保留 15 天的日志 –>
<maxHistory>15</maxHistory>
</rollingPolicy>
<encoder>
<pattern>%date{HH:mm:ss} [%-5level] [%thread] %logger{17} - %m%n </pattern>
</encoder>
</appender>-->
<!-- 用来控制查看那个类的日志内容(对mybatis name 代表命名空间) -->
<logger name="com.changlu" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
<logger name="io.netty.handler.logging.LoggingHandler" level="DEBUG" additivity="false">
<appender-ref ref="STDOUT"/>
</logger>
<root level="ERROR">
<appender-ref ref="STDOUT"/>
</root>
</configuration>
项目目录/data.txt
:文件内容
123456uiopqqrr
src/com/changlu/ByteBufferTest.java
:
import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
/**
* @ClassName ByteBufferTest
* @Author ChangLu
* @Date 2021/12/16 18:55
* @Description ByteBuffer基本使用
*/
@Slf4j
public class ByteBufferTest {
public static void main(String[] args) {
//Channel:①输入输出流取得,如FileChannel。②RandomAccessFile
try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
//准备缓冲区:开辟一块10字节的堆内存空间
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
while (true){
//从channel读取数据,向buffer写入
int len = channel.read(byteBuffer);
log.debug("已读取 {} 个字节", len);
if (len == -1){
break;
}
byteBuffer.flip();//切换 buffer 读模式
// 在buffer中是否还有剩余的内容
while (byteBuffer.hasRemaining()) {
byte data = byteBuffer.get();
log.debug("当前读取的字节为:{}", (char)data);
}
byteBuffer.clear();// 切换 buffer 写模式
}
} catch (IOException e) {
e.printStackTrace();
}
}
}
2.1、ByteBuffer正常使用流程(含源码)
正常流程
- 向 buffer 写入数据,例如调用 channel.read(buffer)
- 调用 flip() 切换至读模式
- 从 buffer 读取数据,例如调用 buffer.get()
- 调用 clear() 或 compact() 切换至写模式
- 重复 1~4 步骤
读写模式源码
//切换为读模式
public final Buffer flip() {
limit = position;//保存已写入的位置
position = 0;//待读取指针指向位置0开始
mark = -1;
return this;
}
//切换为写模式(未读的数据会被直接覆盖)
public final Buffer clear() {
position = 0;//待写入指针指向位置从0开始
limit = capacity;//当前已有数量为原始容量数量(初始化)
mark = -1;
return this;
}
//切换为写模式(压缩未读完的空间至前,之后写入数据依次写入在未读的数据后)
public ByteBuffer compact() {
System.arraycopy(hb, ix(position()), hb, ix(0), remaining());
position(remaining());
limit(capacity());
discardMark();
return this;
}
2.2、ByteBuffer 结构
ByteBuffer 有以下重要属性
- capacity
- position
- limit
一开始(指初创建ByteBuffer对象后):
写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态:
flip()
发生后,position 切换为读取位置,limit 切换为读取限制:
读取 4 个字节后,状态:
clear()
动作发生后,状态:进入写操作
compact()
方法,是把未读完的部分向前压缩,然后切换至写模式
2.3、ByteBuffer方法演示
工具类(图形化显示bytebuffer)
使用方式:
ByteBuffer buffer1 = ByteBuffer.allocate(16);
//调用debugAll即可
ByteBufferUtil.debugAll(buffer1);
工具类:其中使用Netty中的库
import io.netty.util.internal.StringUtil;
import java.nio.ByteBuffer;
import static io.netty.util.internal.MathUtil.isOutOfBounds;
import static io.netty.util.internal.StringUtil.NEWLINE;
public class ByteBufferUtil {
private static final char[] BYTE2CHAR = new char[256];
private static final char[] HEXDUMP_TABLE = new char[256 * 4];
private static final String[] HEXPADDING = new String[16];
private static final String[] HEXDUMP_ROWPREFIXES = new String[65536 >>> 4];
private static final String[] BYTE2HEX = new String[256];
private static final String[] BYTEPADDING = new String[16];
static {
final char[] DIGITS = "0123456789abcdef".toCharArray();
for (int i = 0; i < 256; i++) {
HEXDUMP_TABLE[i << 1] = DIGITS[i >>> 4 & 0x0F];
HEXDUMP_TABLE[(i << 1) + 1] = DIGITS[i & 0x0F];
}
int i;
// Generate the lookup table for hex dump paddings
for (i = 0; i < HEXPADDING.length; i++) {
int padding = HEXPADDING.length - i;
StringBuilder buf = new StringBuilder(padding * 3);
for (int j = 0; j < padding; j++) {
buf.append(" ");
}
HEXPADDING[i] = buf.toString();
}
// Generate the lookup table for the start-offset header in each row (up to 64KiB).
for (i = 0; i < HEXDUMP_ROWPREFIXES.length; i++) {
StringBuilder buf = new StringBuilder(12);
buf.append(NEWLINE);
buf.append(Long.toHexString(i << 4 & 0xFFFFFFFFL | 0x100000000L));
buf.setCharAt(buf.length() - 9, '|');
buf.append('|');
HEXDUMP_ROWPREFIXES[i] = buf.toString();
}
// Generate the lookup table for byte-to-hex-dump conversion
for (i = 0; i < BYTE2HEX.length; i++) {
BYTE2HEX[i] = ' ' + StringUtil.byteToHexStringPadded(i);
}
// Generate the lookup table for byte dump paddings
for (i = 0; i < BYTEPADDING.length; i++) {
int padding = BYTEPADDING.length - i;
StringBuilder buf = new StringBuilder(padding);
for (int j = 0; j < padding; j++) {
buf.append(' ');
}
BYTEPADDING[i] = buf.toString();
}
// Generate the lookup table for byte-to-char conversion
for (i = 0; i < BYTE2CHAR.length; i++) {
if (i <= 0x1f || i >= 0x7f) {
BYTE2CHAR[i] = '.';
} else {
BYTE2CHAR[i] = (char) i;
}
}
}
/**
* 打印所有内容
* @param buffer
*/
public static void debugAll(ByteBuffer buffer) {
int oldlimit = buffer.limit();
buffer.limit(buffer.capacity());
StringBuilder origin = new StringBuilder(256);
appendPrettyHexDump(origin, buffer, 0, buffer.capacity());
System.out.println("+--------+-------------------- all ------------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), oldlimit);
System.out.println(origin);
buffer.limit(oldlimit);
}
/**
* 打印可读取内容
* @param buffer
*/
public static void debugRead(ByteBuffer buffer) {
StringBuilder builder = new StringBuilder(256);
appendPrettyHexDump(builder, buffer, buffer.position(), buffer.limit() - buffer.position());
System.out.println("+--------+-------------------- read -----------------------+----------------+");
System.out.printf("position: [%d], limit: [%d]\n", buffer.position(), buffer.limit());
System.out.println(builder);
}
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put(new byte[]{97, 98, 99, 100});
debugAll(buffer);
}
private static void appendPrettyHexDump(StringBuilder dump, ByteBuffer buf, int offset, int length) {
if (isOutOfBounds(offset, length, buf.capacity())) {
throw new IndexOutOfBoundsException(
"expected: " + "0 <= offset(" + offset + ") <= offset + length(" + length
+ ") <= " + "buf.capacity(" + buf.capacity() + ')');
}
if (length == 0) {
return;
}
dump.append(
" +-------------------------------------------------+" +
NEWLINE + " | 0 1 2 3 4 5 6 7 8 9 a b c d e f |" +
NEWLINE + "+--------+-------------------------------------------------+----------------+");
final int startIndex = offset;
final int fullRows = length >>> 4;
final int remainder = length & 0xF;
// Dump the rows which have 16 bytes.
for (int row = 0; row < fullRows; row++) {
int rowStartIndex = (row << 4) + startIndex;
// Per-row prefix.
appendHexDumpRowPrefix(dump, row, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + 16;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(" |");
// ASCII dump
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append('|');
}
// Dump the last row which has less than 16 bytes.
if (remainder != 0) {
int rowStartIndex = (fullRows << 4) + startIndex;
appendHexDumpRowPrefix(dump, fullRows, rowStartIndex);
// Hex dump
int rowEndIndex = rowStartIndex + remainder;
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2HEX[getUnsignedByte(buf, j)]);
}
dump.append(HEXPADDING[remainder]);
dump.append(" |");
// Ascii dump
for (int j = rowStartIndex; j < rowEndIndex; j++) {
dump.append(BYTE2CHAR[getUnsignedByte(buf, j)]);
}
dump.append(BYTEPADDING[remainder]);
dump.append('|');
}
dump.append(NEWLINE +
"+--------+-------------------------------------------------+----------------+");
}
private static void appendHexDumpRowPrefix(StringBuilder dump, int row, int rowStartIndex) {
if (row < HEXDUMP_ROWPREFIXES.length) {
dump.append(HEXDUMP_ROWPREFIXES[row]);
} else {
dump.append(NEWLINE);
dump.append(Long.toHexString(rowStartIndex & 0xFFFFFFFFL | 0x100000000L));
dump.setCharAt(dump.length() - 9, '|');
dump.append('|');
}
}
public static short getUnsignedByte(ByteBuffer buffer, int index) {
return (short) (buffer.get(index) & 0xFF);
}
}
2.3.1、allocate()、allocateDirect()(分配空间)
各个空间开辟问题:
- 开辟在堆内存的问题:会受到GC垃圾回收的影响,一旦进行GC回收,那么堆内存就会被移动,势必就会造成性能影响。
- 直接内存问题:不会受到GC影响,并非使用的是JVM堆中的内存,使用的是操作系统的。分配比较慢,因为其需要调用操作系统接口,若是使用不当就会造成内存泄漏,需要进行合理的释放。
/**
* @ClassName TestByteBufferAllocate
* @Author ChangLu
* @Date 2021/12/16 20:41
* @Description ByteBufferAllocate:开辟空间
*/
public class TestByteBufferAllocate {
public static void main(String[] args) {
//开启堆内存
System.out.println(ByteBuffer.allocate(10).getClass());
//开辟直接内存
System.out.println(ByteBuffer.allocateDirect(10).getClass());
/*
class java.nio.HeapByteBuffer - java 堆内存,读写效率较低,受到 GC 的影响
class java.nio.DirectByteBuffer - 直接内存,读写效率高(少一次拷贝),不会受 GC 影响,分配的效率低
*/
}
}
2.3.2、put()、flip()、clear()、compact()、get()
import java.nio.ByteBuffer;
import static com.changlu.utils.ByteBufferUtil.debugAll;
public class TestByteBufferReadWrite {
/**
* put():写入字节,position+n
* flip():进入读模式,limit=position,position=0,
* get():读取position开始的字节,position+n
* clear():进入写模式,position=0,limit=capacity
* compact():压缩内容,将未读取的字节向前移,...,position=limit,limit=capacity
*
* @param args
*/
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(16);
//写入一个字节
buffer.put((byte)0x61);
debugAll(buffer);
//进入读模式
buffer.flip();
debugAll(buffer);
//读取一个字节
System.out.println("读取字符:" + (char)buffer.get());
debugAll(buffer);
//测试compact():切换写模式,写入三个字节,切换读模式,读取一个字节,进行压缩(保留未读字节向前移动,position指向未读字节之后)
buffer.clear();
buffer.put(new byte[]{0x62,0x63,0x64});
buffer.flip();
System.out.println("读取字符:" + (char)buffer.get());
buffer.compact();
debugAll(buffer);
}
}
效果:
+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [16]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |a...............|
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [1]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |a...............|
+--------+-------------------------------------------------+----------------+
读取字符:a
+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [1]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 00 00 00 00 00 00 00 00 00 00 00 00 00 00 00 |a...............|
+--------+-------------------------------------------------+----------------+
读取字符:b
+--------+-------------------- all ------------------------+----------------+
position: [2], limit: [16]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 63 64 64 00 00 00 00 00 00 00 00 00 00 00 00 00 |cdd.............|
+--------+-------------------------------------------------+----------------+
2.3.3、get()、put()(读取与写入数据)
读取
同样有两种办法
- 调用 channel 的 write 方法
- 调用 buffer 自己的 get 方法
int writeBytes = channel.write(buf);//从bytebuffer中读取写入到channel中
和
byte b = buf.get();//直接从bytebuffer中取到1个字节
get 方法会让 position 读指针向后走,如果想重复读取数据
- 可以调用 rewind 方法将 position 重新置为 0
- 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针position!
写入
有两种办法
- 调用 channel 的 read 方法
- 调用 buffer 自己的 put 方法
int readBytes = channel.read(buf);//从channel中读取到数据写入到bytebuffer里
和
buf.put((byte)127);//直接向bytebuffer写入一个字节
2.3.4、rewind()(重置position=0)
目的:想要重新重头读取一遍数据。
import java.nio.ByteBuffer;
import static com.changlu.utils.ByteBufferUtil.debugAll;
/**
* @ClassName TestByteBufferRewind
* @Author ChangLu
* @Date 2021/12/16 20:51
* @Description 测试ByteBuffer的Rewind()方法
*/
public class TestByteBufferRewind {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(10);
buffer.put(new byte[]{0x61,0x62,0x63});
buffer.flip();
debugAll(buffer);
for (int i = 0; i < 3; i++) {
if (i == 0)
System.out.print("读取三个字节:");
System.out.print((char)buffer.get() + " ");
}
System.out.println();
debugAll(buffer);
//rewind()(重复读取一遍):position = 0
buffer.rewind();
System.out.println("执行rewind后:");
debugAll(buffer);
System.out.println("重新读取一遍:");
for (int i = 0; i < 3; i++) {
if (i == 0)
System.out.print("读取三个字节:");
System.out.print((char)buffer.get() + " ");
}
}
}
效果:
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [3]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 00 00 00 00 00 00 00 |abc....... |
+--------+-------------------------------------------------+----------------+
读取三个字节:a b c
+--------+-------------------- all ------------------------+----------------+
position: [3], limit: [3]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 00 00 00 00 00 00 00 |abc....... |
+--------+-------------------------------------------------+----------------+
执行rewind后:
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [3]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 61 62 63 00 00 00 00 00 00 00 |abc....... |
+--------+-------------------------------------------------+----------------+
重新读取一遍:
读取三个字节:a b c
2.3.5、remark()与reset()(打标记与重置指针位置)
目的:若是我们想要重复读某个指定位置开始的内容,可使用标记与恢复标记的方式进行。
import java.nio.ByteBuffer;
import static com.changlu.utils.ByteBufferUtil.debugAll;
/**
* @ClassName TestByteBufferMark_Reset
* @Author ChangLu
* @Date 2021/12/16 21:03
* @Description 测试ByteBuffer的方法:mark()、reset()
*/
public class TestByteBufferMark_Reset {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer.put(new byte[]{0x62,0x63,0x64});
buffer.flip();
System.out.println((char)buffer.get());
buffer.mark();//mark进行标记该位置:mark=position
System.out.println((char)buffer.get());
System.out.println((char)buffer.get());
debugAll(buffer);
buffer.reset();//恢复到原标记位置:position=mark
debugAll(buffer);
//重复读两次
System.out.println("恢复标记后,重新读取:");
System.out.println((char)buffer.get());
System.out.println((char)buffer.get());
}
}
效果展示:
b
c
d
+--------+-------------------- all ------------------------+----------------+
position: [3], limit: [3]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 00 00 00 00 00 00 00 00 00 00 00 00 00 |bcd.............|
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [1], limit: [3]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 62 63 64 00 00 00 00 00 00 00 00 00 00 00 00 00 |bcd.............|
+--------+-------------------------------------------------+----------------+
恢复标记后,重新读取:
c
d
2.3.6、String与ByteBuffer互转
其中StandardCharsets.UTF_8.encode
进行编码得到的ByteBuffer对象会进行转换读模式(position=0)!
import java.nio.ByteBuffer;
import java.nio.charset.StandardCharsets;
import static com.changlu.utils.ByteBufferUtil.debugAll;
/**
* @ClassName TestStringTOByteBuffer
* @Author ChangLu
* @Date 2021/12/16 21:13
* @Description String与ByteBuffer互转
*/
public class TestStringTOByteBuffer {
public static void main(String[] args) {
ByteBuffer buffer = ByteBuffer.allocate(16);
//字符串转为bytebuffer
//方式一:put()时直接字符串转为byte[]写入
buffer.put("changlu".getBytes());
debugAll(buffer);
//方式二:StandardCharsets.UTF_8进行编码创建对象。
//内部过程:按需创建空间,依次填入内容后,执行写模式
ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("changlu");
debugAll(buffer2);
//方式三:ByteBuffer.wrap()
ByteBuffer buffer3 = ByteBuffer.wrap("changlu".getBytes());
debugAll(buffer3);
//ByteBuffer转字符串
//方式一:StandardCharsets.UTF_8.decode,原理就是从position位置开始读取已有的内容
System.out.println(StandardCharsets.UTF_8.decode(buffer2).toString());
//注意:对于上面方式一put()进入由于没有转换为读状态所以需要先进行转换状态,也就是要position=0
buffer.flip();
System.out.println(StandardCharsets.UTF_8.decode(buffer).toString());
}
}
效果:
+--------+-------------------- all ------------------------+----------------+
position: [7], limit: [16]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 63 68 61 6e 67 6c 75 00 00 00 00 00 00 00 00 00 |changlu.........|
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [7]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 63 68 61 6e 67 6c 75 |changlu |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [7]
+-------------------------------------------------+
| 0 1 2 3 4 5 6 7 8 9 a b c d e f |
+--------+-------------------------------------------------+----------------+
|00000000| 63 68 61 6e 67 6c 75 |changlu |
+--------+-------------------------------------------------+----------------+
changlu
changlu
快速总结
ByteBuffer方法:
方法 | 效果 |
---|---|
put() | postion += n |
get() | position += n |
get(index) | 直接取到内容,position不动 |
flip() | 读状态:limit = position,position=0 |
clear() | 写状态:position=0 |
compact() | 写状态:未读数据压缩,position=limit+1,limit=capacity |
rewind() | 重置:position=0 |
remark() | mark=position |
reset() | position=mark |
String与ByteBuffer互转方法:
String => ByteBuffer
方法 | 效果 |
---|---|
buffer.put(“changlu”.getBytes()) | 写入方式,position += n |
StandardCharsets.UTF_8.encode(“changlu”) | 按需创建空间,position = 0 |
ByteBuffer.wrap(“changlu”.getBytes()) | 按需创建空间,position = 0 |
ByteBuffer => String
方法 | 效果 |
---|---|
StandardCharsets.UTF_8.decode(buffer2).toString() | 需要当前的buffer为读模式,也就是position应当为0 |
- 点赞
- 收藏
- 关注作者
评论(0)