ByteBuffer使用实例
ByteBuffer作为JDK的字节流处理对象,这里举个小例子说明下用法,直接上代码:
package com.wlf.netty.nettyserver; import org.junit.Assert;
import org.junit.Test; import java.nio.ByteBuffer; public class ByteBufferTest { @Test
public void byteBufferTest() { // 写入消息体
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
byteBuffer.putInt(0xabef0101);
byteBuffer.putInt(1024); // 今天过节
byteBuffer.put((byte) 1);
byteBuffer.put((byte) 0); // 读取消息头,因为写完后position已经到10了,所以需要先反转为0,再从头读取
byteBuffer.flip();
printDelimiter(byteBuffer); // 读取length
printLength(byteBuffer); // 继续读取剩下数据
byteBuffer.get();
byteBuffer.get();
printByteBuffer(byteBuffer); // 我再反转一下,我还可以从头开始读
byteBuffer.flip();
printDelimiter(byteBuffer); // clear清空一下,再从头开始读
byteBuffer.clear();
printDelimiter(byteBuffer); // rewind重绕一下
byteBuffer.rewind();
printDelimiter(byteBuffer); // mark标记一下
byteBuffer.mark(); // 再读取length
printLength(byteBuffer); // reset重置,回到读取delimiter的地方
byteBuffer.reset();
printByteBuffer(byteBuffer);
} private void printDelimiter(ByteBuffer buf) {
int newDelimiter = buf.getInt();
System.out.printf("delimeter: %s\n", Integer.toHexString(newDelimiter));
printByteBuffer(buf);
} private void printLength(ByteBuffer buf) {
int length = buf.getInt();
System.out.printf("length: %d\n", length);
printByteBuffer(buf);
} private void printByteBuffer(ByteBuffer buf) {
System.out.printf("position: %d, limit: %d, capacity: %d\n", buf.position(), buf.limit(), buf.capacity());
}
}
输出结果:
delimeter: abef0101
position: 4, limit: 10, capacity: 10
length: 1024
position: 8, limit: 10, capacity: 10
position: 10, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
delimeter: abef0101
position: 4, limit: 10, capacity: 10
length: 1024
position: 8, limit: 10, capacity: 10
position: 4, limit: 10, capacity: 10 Process finished with exit code 0
ByteBuffer的索引是唯一的。像上面的例子,初始索引是0,写完索引值为9,为了读取写入的值,我们再重新设置索引为0(调用flip方法)。ByteBuffer有4个索引值,分别是:
mask:就是你标记的索引,标记唯一的作用是调用reset重置回到过去
position:当前位置的索引,mask标记任何时候都不会大于position,因为你必须先读到当前位置之后,才能标记该位置;同时position也不能超过limit限制
limit:第一个不应该读取或写入的元素的索引,也就是读写禁地,默认是最大容量,如果你设置该值,那么理所让然它不能超过最大容量capacity
capacity:这个就不解释了
它们的大小关系始终是:
mask <= position <= limit <= capacity
我们上面的例子中就是capacity=limit。
初始索引:
+-----------------------------------------------------+
/ bytes /
+-----------------------------------------------------+
/ 10 /
0=position 10=limit=capacity
我们写入delimiter之后:
+----------------+------------------------------------+
/ delimiter / other bytes /
+----------------+------------------------------------+
/ 4 / 6 /
0 4=position 10=limit=capacity
至于反转flip如何切换读写模式、reset如何重置标记、clear清除如何重新设置索引值为0、rewind重绕如何让你重新读取,都不会动内容,所以你会看到上面不管怎么折腾我们都可以重复取出delimiter、length的值。看下源码就一清二楚了,无非就是对上面4个索引值进行赋值而已:
/**
* Resets this buffer's position to the previously-marked position.
*
* <p> Invoking this method neither changes nor discards the mark's
* value. </p>
*
* @return This buffer
*
* @throws InvalidMarkException
* If the mark has not been set
*/
public final Buffer reset() {
int m = mark;
if (m < 0)
throw new InvalidMarkException();
position = m;
return this;
} /**
* Clears this buffer. The position is set to zero, the limit is set to
* the capacity, and the mark is discarded.
*
* <p> Invoke this method before using a sequence of channel-read or
* <i>put</i> operations to fill this buffer. For example:
*
* <blockquote><pre>
* buf.clear(); // Prepare buffer for reading
* in.read(buf); // Read data</pre></blockquote>
*
* <p> This method does not actually erase the data in the buffer, but it
* is named as if it did because it will most often be used in situations
* in which that might as well be the case. </p>
*
* @return This buffer
*/
public final Buffer clear() {
position = 0;
limit = capacity;
mark = -1;
return this;
} /**
* Flips this buffer. The limit is set to the current position and then
* the position is set to zero. If the mark is defined then it is
* discarded.
*
* <p> After a sequence of channel-read or <i>put</i> operations, invoke
* this method to prepare for a sequence of channel-write or relative
* <i>get</i> operations. For example:
*
* <blockquote><pre>
* buf.put(magic); // Prepend header
* in.read(buf); // Read data into rest of buffer
* buf.flip(); // Flip buffer
* out.write(buf); // Write header + data to channel</pre></blockquote>
*
* <p> This method is often used in conjunction with the {@link
* java.nio.ByteBuffer#compact compact} method when transferring data from
* one place to another. </p>
*
* @return This buffer
*/
public final Buffer flip() {
limit = position;
position = 0;
mark = -1;
return this;
} /**
* Rewinds this buffer. The position is set to zero and the mark is
* discarded.
*
* <p> Invoke this method before a sequence of channel-write or <i>get</i>
* operations, assuming that the limit has already been set
* appropriately. For example:
*
* <blockquote><pre>
* out.write(buf); // Write remaining data
* buf.rewind(); // Rewind buffer
* buf.get(array); // Copy data into array</pre></blockquote>
*
* @return This buffer
*/
public final Buffer rewind() {
position = 0;
mark = -1;
return this;
}
ByteBuffer使用实例的更多相关文章
- ByteBuffer常用方法详解
原文 http://blog.csdn.net/u012345283/article/details/38357851 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I/ ...
- ByteBuf使用实例
之前我们有个netty5的拆包解决方案(参加netty5拆包问题解决实例),现在我们采用另一种思路,不需要新增LengthFieldBasedFrameDecoder,直接修改NettyMessage ...
- JAVA NIO缓冲区(Buffer)------ByteBuffer常用方法
参考:https://blog.csdn.net/xialong_927/article/details/81044759 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I ...
- Java性能优化之使用NIO提升性能(Buffer和Channel)
在软件系统中,由于IO的速度要比内存慢,因此,I/O读写在很多场合都会成为系统的瓶颈.提升I/O速度,对提升系统整体性能有着很大的好处. 在Java的标准I/O中,提供了基于流的I/O实现,即Inpu ...
- Java NIO Buffer(netty源码死磕1.2)
[基础篇]netty源码死磕1.2: NIO Buffer 1. Java NIO Buffer Buffer是一个抽象类,位于java.nio包中,主要用作缓冲区.Buffer缓冲区本质上是一块可 ...
- JAVA NIO学习笔记二 频道和缓冲区
Java NIO 频道 Java NIO渠道类似于流,他们之间具有一些区别的: 您可以读取和写入频道.流通常是单向(读或写). 通道可以异步读取和写入数据. 通道常常是读取或写入缓冲区. 如上所述,您 ...
- LWJGL3的内存管理,第一篇,基础知识
LWJGL3的内存管理,第一篇,基础知识 为了讨论LWJGL在内存分配方面的设计,我将会分为数篇随笔分开介绍,本篇将主要介绍一些大方向的问题和一些必备的知识. 何为"绑定(binding)& ...
- 最近学习工作流 推荐一个activiti 的教程文档
全文地址:http://www.mossle.com/docs/activiti/ Activiti 5.15 用户手册 Table of Contents 1. 简介 协议 下载 源码 必要的软件 ...
- RPC原理及RPC实例分析
在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...
随机推荐
- Django REST framework认证权限和限制 源码分析
1.首先 我们进入这个initial()里面看下他内部是怎么实现的. 2.我们进入里面看到他实现了3个方法,一个认证,权限频率 3.我们首先看下认证组件发生了什么 权限: 啥都没返回,self.per ...
- 一个简单的直播demo for java
obs推流,nginx挂rtmp模块,配置rtmp端口,obs向此端口推流,video.js H5拉流播放 加阿里CDN 超级简单- -
- asp.net+ueditor word粘贴上传
最近公司做项目需要实现一个功能,在网页富文本编辑器中实现粘贴Word图文的功能. 我们在网站中使用的Web编辑器比较多,都是根据用户需求来选择的.目前还没有固定哪一个编辑器 有时候用的是UEditor ...
- POJ 2778 DNA Sequence (矩阵快速幂 + AC自动鸡)
题目:传送门 题意: 给你m个病毒串,只由(A.G.T.C) 组成, 问你生成一个长度为 n 的 只由 A.C.T.G 构成的,不包含病毒串的序列的方案数. 解: 对 m 个病毒串,建 AC 自动机, ...
- jsp页面解析出错,或出现下载情况.
当没有下面代码时,会出现空白页的bug <dependency> <groupId>org.apache.tomcat.embed</groupId> <ar ...
- Jenkins 通过 maven 构建编译 JAVA 项目环境
Jenkins 通过maven 构建编译 JAVA 项目环境 官网下载合适Jenkins版本包: 1.jenkins http://mirrors.jenkins.io/war-stable/ 2.J ...
- 一个 Object.assign 的误解
mozilla中对 Object.assign 的解释如下地址: mozilla 其中有说到 注意, Object.assign 会跳过那些值为 null 或 undefined 的源对象. 一直以为 ...
- java学习笔记(3)数据类型、源码、反码、补码、精度损失、基本数据类型互相转换
关于java中的数据类型: 1.数据类型的作用是什么? 程序当中有很多数据,每一个数据都是有相关类型的,不同数据类型的数据占用的空间大小不同. 数据类型的作用是指导java虚拟机(JVM)在运行程序的 ...
- Java SpringBoot使用126邮箱发送html内容邮件,带附件
package mail.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframewor ...
- 记录vsCode配置node开发环境
环境:win10,idea:vscode 1:安装Visual Studio Code 下一步下一步.(很早之前就安装了). 2:安装node. http://nodejs.cn/download/ ...