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使用实例的更多相关文章

  1. ByteBuffer常用方法详解

    原文  http://blog.csdn.net/u012345283/article/details/38357851 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I/ ...

  2. ByteBuf使用实例

    之前我们有个netty5的拆包解决方案(参加netty5拆包问题解决实例),现在我们采用另一种思路,不需要新增LengthFieldBasedFrameDecoder,直接修改NettyMessage ...

  3. JAVA NIO缓冲区(Buffer)------ByteBuffer常用方法

    参考:https://blog.csdn.net/xialong_927/article/details/81044759 缓冲区(Buffer)就是在内存中预留指定大小的存储空间用来对输入/输出(I ...

  4. Java性能优化之使用NIO提升性能(Buffer和Channel)

    在软件系统中,由于IO的速度要比内存慢,因此,I/O读写在很多场合都会成为系统的瓶颈.提升I/O速度,对提升系统整体性能有着很大的好处. 在Java的标准I/O中,提供了基于流的I/O实现,即Inpu ...

  5. Java NIO Buffer(netty源码死磕1.2)

    [基础篇]netty源码死磕1.2:  NIO Buffer 1. Java NIO Buffer Buffer是一个抽象类,位于java.nio包中,主要用作缓冲区.Buffer缓冲区本质上是一块可 ...

  6. JAVA NIO学习笔记二 频道和缓冲区

    Java NIO 频道 Java NIO渠道类似于流,他们之间具有一些区别的: 您可以读取和写入频道.流通常是单向(读或写). 通道可以异步读取和写入数据. 通道常常是读取或写入缓冲区. 如上所述,您 ...

  7. LWJGL3的内存管理,第一篇,基础知识

    LWJGL3的内存管理,第一篇,基础知识 为了讨论LWJGL在内存分配方面的设计,我将会分为数篇随笔分开介绍,本篇将主要介绍一些大方向的问题和一些必备的知识. 何为"绑定(binding)& ...

  8. 最近学习工作流 推荐一个activiti 的教程文档

    全文地址:http://www.mossle.com/docs/activiti/ Activiti 5.15 用户手册 Table of Contents 1. 简介 协议 下载 源码 必要的软件 ...

  9. RPC原理及RPC实例分析

    在学校期间大家都写过不少程序,比如写个hello world服务类,然后本地调用下,如下所示.这些程序的特点是服务消费方和服务提供方是本地调用关系. 1 2 3 4 5 6 public class ...

随机推荐

  1. mysql数据库中的多表查询(内连接,外连接,子查询)

    用两个表(a_table.b_table),关联字段a_table.a_id和b_table.b_id来演示一下MySQL的内连接.外连接( 左(外)连接.右(外)连接.全(外)连接). MySQL版 ...

  2. 02 c++的封装性 (构造和析构)

    封装性: 关键字:public private protected 破坏封装:友元函数 friend 实现数据的隐藏:class类 默认是私有,结构体默认是公有. 类和对象:(定义类的注意事项) 在类 ...

  3. 记录一下使用swiper遇到的坑

    loop 设置为true 则开启loop模式.loop模式:会在原本slide前后复制若干个slide(默认一个)并在合适的时候切换,让Swiper看起来是循环的. loop模式在与free模式同用时 ...

  4. 适合于做项目与团队管理的工具(Choerodon)

    官网链接:http://choerodon.io/zh/ 此处不做太多的介绍,需要了解的朋友进入官网进行查看. Choerodon猪齿鱼开源多云技术平台,是基于开源技术Kubernetes,Istio ...

  5. SpringBoot官方文档学习(三)配置文件、日志、国际化和JSON

    一.Profiles Spring配置文件提供了一种方法来隔离应用程序配置的各个部分,并使其仅在某些环境中可用.任何@Component.@Configuration或@ConfigurationPr ...

  6. 学习Spring-Data-Jpa(二)---JPA基本注解

    基本注解 1.@Entity :用于添加在实体类上,定义该JAVA类成为被JPA管理的实体,将映射到指定的数据库表.如定义一个实体类Category,它将映射到数据库中的category表中. 2.@ ...

  7. js通过html的url获取参数值

    function getUrlParameter(name){ name = name.replace(/[]/,"\[").replace(/[]/,"\[" ...

  8. 浏览器在线预览pdf、txt、office文件

    //使用文件预览的原因是:TMD微信浏览器屏蔽掉文件下载链接,只好折中使用文件在线预览功能//要点:1.office文件用微软的插件打开 http://view.officeapps.live.com ...

  9. [HAOI2015][bzoj 4033]树上染色(树dp+复杂度分析)

    [题目描述]有一棵点数为N的树,树边有边权.给你一个在0~N之内的正整数K,你要在这棵树中选择K个点,将其染成黑色,并将其他的N-K个点染成白色.将所有点染色后,你会获得黑点两两之间的距离加上白点两两 ...

  10. NOIP前做题记录

    鉴于某些原因(主要是懒)就不一题一题写了,代码直接去\(OJ\)上看吧 CodeChef Making Change 传送门 完全没看懂题解在讲什么(一定是因为题解公式打崩的原因才不是曲明英语太差呢- ...