ByteBuffer作为老牌的字节流处理对象,这里举个小例子说明下用法,直接上代码:
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
原文:https://www.cnblogs.com/wuxun1997/p/11735826.html