一个可以形象展示ByteBuffer内容的方法,便于调试
package com.example.netty;import java.nio.ByteBuffer;public class ByteBufferUtil {/*** 打印ByteBuffer的内容,以十六进制和ASCII字符的形式展示。** @param buffer 要展示的ByteBuffer*/public static void debugByteBuffer(ByteBuffer buffer) {// 重置buffer的位置,以便从头开始读取buffer.rewind();// 用于存储十六进制字符串StringBuilder hexDump = new StringBuilder();// 用于存储ASCII字符StringBuilder asciiDump = new StringBuilder();// 一次读取一个字节while (buffer.hasRemaining()) {int byteValue = buffer.get() & 0xFF; // 确保是正数// 添加到十六进制字符串hexDump.append(String.format("%02X ", byteValue));// 添加到ASCII字符串,如果是不可打印的字符,则显示为点char ch = (char) byteValue;asciiDump.append((ch >= 32 && ch <= 126) ? ch : '.');// 每行16个字节if (buffer.position() % 16 == 0) {hexDump.append(" ").append(asciiDump);hexDump.append(System.lineSeparator());asciiDump.setLength(0); // 清空ASCII字符串}}// 如果最后一行不足16个字节,也打印出来if (asciiDump.length() > 0) {// 补足空格,保持对齐while (hexDump.length() < 48) {hexDump.append(" ");}hexDump.append(asciiDump);}// 打印结果System.out.println(hexDump.toString());}public static void main(String[] args) {// 示例:创建一个ByteBuffer并填充一些数据ByteBuffer buffer = ByteBuffer.allocate(64);for (int i = 0; i < buffer.capacity(); i++) {buffer.put((byte) i);}// 展示ByteBuffer内容debugByteBuffer(buffer);}
}
可以展现出如下结果: