1. 测试ByteBuffer

1.1 依赖

<dependencies>
        <dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.48.Final</version>
        </dependency>

        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.18.20</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.6</version>
        </dependency>

        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>20.0</version>
        </dependency>

        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.4</version>
        </dependency>
    </dependencies>

1.2 新建文本文件data.txt

15354154154aahbaj

1.3 使用 FileChannel 来读取文件内容

输入或输出流,或者RandomAccessFile获取FileChannel

public static void main(String[] args) {
        // 输入或输出流获得 ,或者RandomAccessFile获取FileChannel
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            // 准备缓冲区  缓冲区10字节
            ByteBuffer buffer = ByteBuffer.allocate(10);
            int len = -1;
            while ((len = channel.read(buffer)) != -1) {
                log.debug("读取到的字节数{}", len);
                // 切换buffer为读模式就可以获取数据
                buffer.flip();
                while (buffer.remaining() > 0) {
                    byte b = buffer.get();
                    log.debug("读取到的字符{}", (char) b);
                }
                // 却换为写模式
                buffer.clear();
            }
        } catch (IOException e) {
        }        
    }

2. ByteBuffer正确使用步骤

ByteBuffer初始是写状态

  1. 向 buffer 写入数据,例如调用 channel.read(buffer)
  2. 调用 flip() 切换至读模式
  3. 从 buffer 读取数据,例如调用 buffer.get()
  4. 调用 clear() 或 compact() 切换至写模式
  5. 重复 1~4 步骤

3. ByteBuffer 结构

ByteBuffer 有以下重要属性

  • capacity
  • position
  • limit

一开始

android bytebuffer 读取 读取bytebuffer里的内容_netty

写模式下,position 是写入位置,limit 等于容量,下图表示写入了 4 个字节后的状态

android bytebuffer 读取 读取bytebuffer里的内容_i++_02

flip 动作发生后,position 切换为读取位置,limit 切换为读取限制

android bytebuffer 读取 读取bytebuffer里的内容_System_03

读取 4 个字节后,状态

android bytebuffer 读取 读取bytebuffer里的内容_System_04

clear 动作发生后,状态

android bytebuffer 读取 读取bytebuffer里的内容_System_05

compact 方法,是把未读完的部分向前压缩,然后切换至写模式

android bytebuffer 读取 读取bytebuffer里的内容_System_06

4. ByteBuffer调试工具类

package com.wang.c1;

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);
    }

    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);
    }
}

5. ByteBuffer 常见方法

5.1 分配空间

  • allocate()
  • allocateDirect()
public static void main(String[] args) {
        System.out.println(ByteBuffer.allocate(16).getClass());
        System.out.println(ByteBuffer.allocateDirect(16).getClass());
        /**
         * class java.nio.HeapByteBuffer  使用堆内存 , 读写效率低, 受到gc影响
         * class java.nio.DirectByteBuffer  使用直接内存: 读写效率高, 不受到gc影响, 分配的效率低, 可能造成内存泄漏
         */
    }

5.2 向buffer中写入数据

  • 调用 channel 的 read 方法
int readBytes = channel.read(buf);
  • 调用 buffer 自己的 put 方法
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
 byteBuffer.put(new byte[] {'a', 'b', 'c', 'd'});

5.3 从 buffer 读取数据

byteBuffer.flip();
    // 从头开始读
    byteBuffer.get(new byte[4]);

5.4 改变position 指针位置

5.4.1 rewind()

get 方法会让 position 读指针向后走,如果想重复读取数据

  • 可以调用 rewind 方法将 position 重新置为 0
  • 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        byteBuffer.put(new byte[] {'a', 'b', 'c', 'd'});
        byteBuffer.flip();
        // 从头开始读
        byteBuffer.get(new byte[4]);
        ByteBufferUtil.debugAll(byteBuffer);

        // 把position 改为零, 又可以重头读
        byteBuffer.rewind();
        ByteBufferUtil.debugAll(byteBuffer);

5.4.2 mark 和 reset

mark 是在读取时,做一个标记,即使 position 改变,只要调用 reset 就能回到 mark 的位置

rewind 和 flip 都会清除 mark 位置

ByteBuffer byteBuffer2 = ByteBuffer.allocate(10);
        byteBuffer2.put(new byte[] {'a', 'b', 'c', 'd'});
        byteBuffer2.flip();
        ByteBufferUtil.debugAll(byteBuffer2);
        byteBuffer2.get();
        // 下标为1位置标记
        byteBuffer2.mark();
        byteBuffer2.get();
        byteBuffer2.get();
        ByteBufferUtil.debugAll(byteBuffer2);
        byteBuffer2.reset();
        ByteBufferUtil.debugAll(byteBuffer2);

android bytebuffer 读取 读取bytebuffer里的内容_ci_07

5.5 字符串与 ByteBuffer 互转

5.5.1 字符串转为ByteBuffer

5.5.1.1 put
ByteBuffer byteBuffer = ByteBuffer.allocate(10);
 String str = "hello";
 byteBuffer.put(str.getBytes());
 ByteBufferUtil.debugAll(byteBuffer);
5.5.1.2 CharSet

CharSet , 自动切换到读模式

ByteBuffer byteBuffer1 = StandardCharsets.UTF_8.encode(str);
ByteBufferUtil.debugAll(byteBuffer1);
5.5.1.3 wrap

wrap, 自动切换到读模式

ByteBuffer byteBuffer2 = ByteBuffer.wrap(str.getBytes());
 ByteBufferUtil.debugAll(byteBuffer2);

5.5.2 ByteBuffer转化为字符串

String s = StandardCharsets.UTF_8.decode(byteBuffer1).toString();

6. 分散读取和集中写入

6.1 分散读取

有一个文本文件 3parts.txt

onetwothree

使用如下方式读取,可以将数据填充至多个 buffer

public static void main(String[] args) {
        try (FileChannel channel = new RandomAccessFile("3parts.txt","r").getChannel()) {
            ByteBuffer b1 = ByteBuffer.allocate(3);
            ByteBuffer b2 = ByteBuffer.allocate(3);
            ByteBuffer b3 = ByteBuffer.allocate(5);

            channel.read(new ByteBuffer[] {b1, b2, b3});

            ByteBufferUtil.debugAll(b1);
            ByteBufferUtil.debugAll(b2);
            ByteBufferUtil.debugAll(b3);
        } catch (IOException e) {
        }
    }

android bytebuffer 读取 读取bytebuffer里的内容_netty_08

6.2 集中写

public static void main(String[] args) {
        ByteBuffer b1 = StandardCharsets.UTF_8.encode("hello");
        ByteBuffer b2 = StandardCharsets.UTF_8.encode("java");
        ByteBuffer b3 = StandardCharsets.UTF_8.encode("!");

        try (FileChannel channel = new RandomAccessFile("words.txt", "rw").getChannel()) {
            channel.write(new ByteBuffer[] {b1, b2, b3});
        } catch (IOException e) {
        }
    }