NIO知识总结二

4. Buffer

4.1 简介

Java NIO 中的 Buffer 用于和 NIO 通道进行交互。数据是从通道读入缓冲区,从缓冲区写入到通道中的。

image-20220924222018621

缓冲区本质上是一块可以写入数据,然后可以从中读取数据的内存。这块内存被包装成 NIO Buffer 对象,并提供了一组方法,用来方便

的访问该块内存。缓冲区实际上是一个容器对象,更直接的说,其实就是一个数组,在 NIO 库中,所有数据都是用缓冲区处理的。在读

取数据时,它是直接读到缓冲区中的; 在写入数据时,它也是写入到缓冲区中的;任何时候访问 NIO 中的数据,都是将它放到缓冲区

中。而在面向流 I/O系统中,所有数据都是直接写入或者直接将数据读取到 Stream 对象中。

4.2 使用方法

使用 Buffer 读写数据,一般遵循以下四个步骤

  1. 写入数据到 Buffer
  2. 调用 flip()方法
  3. 从 Buffer 中读取数据,例如调用 buffer.get()
  4. 调用 clear()方法或者 compact()方法

当向 buffer 写入数据时,buffer 会记录下写了多少数据。一旦要读取数据,需要通过 flip() 方法将 Buffer 从写模式切换到读模式。在读

模式下,可以读取之前写入到 buffer的所有数据。一旦读完了所有的数据,就需要清空缓冲区,让它可以再次被写入。有两种方式能清空

缓冲区:调用 clear()或 compact()方法。clear()方法会清空整个缓冲区。compact()方法只会清除已经读过的数据。任何未读的数据都被

移到缓冲区的起始处,新写入的数据将放到缓冲区未读数据的后面。

演示:有一普通文本文件 data.txt,内容为

1234567890abcd

使用 FileChannel 来读取文件内容

public static void main(String[] args) {
    // 获取FileChannel
    // 1. 输入输出流 2. RandomAccessFile
    try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
        // 准备缓冲区
        ByteBuffer byteBuffer = ByteBuffer.allocate(10);
        while (true) {
            // 从channel 读取数据,向byteBuffer写入
            int len = channel.read(byteBuffer);
            log.debug("读取到的字节数:{}", len);
            if (len == -1) {
                // 没有内容了
                break;
            }
            // 打印byteBuffer的内容
            byteBuffer.flip();  // 切换至读模式
            while (byteBuffer.hasRemaining()) {
                byte b = byteBuffer.get();
                log.debug("读取到的字节:{}", (char) b);
            }
            // 切换为写模式
            byteBuffer.clear();
        }

    } catch (Exception e) {
    }
}

输出

20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节数:10
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:1
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:2
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:3
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:4
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:5
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:6
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:7
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:8
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:9
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:0
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节数:4
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:a
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:b
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:c
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节:d
20:19:38 [DEBUG] [main] c.lt.NettyTests - 读取到的字节数:-1

4.3 ByteBuffer 结构

ByteBuffer 有以下重要属性

  • capacity
  • position
  • limit

一开始

image-20220923202413521

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

image-20220923202538130

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

image-20220923202550285

读取4个字节后,状态

image-20220923202609301

clear动作发生后,状态

image-20220923202621408

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

image-20220923202754443

4.3.1 调试工具类
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);
    }
}

4.4 ByteBuffer 常见方法

4.4.1 分配空间

可以使用allocate方法为ByteBuffer分配空间,其它buffer类也有该方法

System.out.println(ByteBuffer.allocate(16).getClass());
System.out.println(ByteBuffer.allocateDirect(16).getClass());
/**
 * class java.nio.HeapByteBuffer    --- Java 堆内存 读写效率较低,收到 GC 的影响
 * class java.nio.DirectByteBuffer  --- 直接内存(系统内存) 读写效率高(少一次拷贝),不会受 GC 影响,但分配的效率低,可能会内存泄露
 */
4.4.2 向 buffer 写入数据

有两种办法

  • 调用 channel 的 read 方法—从 Channel 读取数据,向 Buffer 写入
  • 调用 buffer 自己的 put 方法
int readBytes = channel.read(buf);
buf.put((byte)127);
4.4.3 从 buffer 读取数据

同样有两种办法

  • 调用 channel 的 write 方法—从 Buffer 读取,向 Channel 写入
  • 调用 buffer 自己的 get 方法
int writeBytes = channel.write(buf);
byte b = buf.get();

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

  • 可以调用 rewind 方法将 position 重新置为 0
  • 或者调用 get(int i) 方法获取索引 i 的内容,它不会移动读指针
4.4.4 mark 和 reset

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

注意

rewindflip 都会清除 mark 位置

4.4.5 字符串与 ByteBuffer 互转
// 1. 字符串转为 ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(16);
buffer.put("hello".getBytes(StandardCharsets.UTF_8));
debugAll(buffer);

// 2. Charset
ByteBuffer buffer2 = StandardCharsets.UTF_8.encode("hello");    // 自动切换为读模式
debugAll(buffer2);

// 3. wrap
ByteBuffer buffer3 = ByteBuffer.wrap("hello".getBytes(StandardCharsets.UTF_8)); // 自动切换为读模式
debugAll(buffer3);

// ByteBuffer 转为字符串
// 要 ByteBuffer 为读模式才可以
buffer.flip();
String str1 = StandardCharsets.UTF_8.decode(buffer).toString();
System.out.println(str1);
String str2 = StandardCharsets.UTF_8.decode(buffer2).toString();
System.out.println(str2);

输出

+--------+-------------------- all ------------------------+----------------+
position: [5], limit: [16]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f 00 00 00 00 00 00 00 00 00 00 00 |hello...........|
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [5]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f                                  |hello           |
+--------+-------------------------------------------------+----------------+
+--------+-------------------- all ------------------------+----------------+
position: [0], limit: [5]
         +-------------------------------------------------+
         |  0  1  2  3  4  5  6  7  8  9  a  b  c  d  e  f |
+--------+-------------------------------------------------+----------------+
|00000000| 68 65 6c 6c 6f                                  |hello           |
+--------+-------------------------------------------------+----------------+
hello
hello

注意:Buffer 是非线程安全的

4.5 缓冲区操作

4.5.1 缓冲区分片

在 NIO 中,除了可以分配或者包装一个缓冲区对象外,还可以根据现有的缓冲区对象来创建一个子缓冲区,即在现有缓冲区上切出一片

来作为一个新的缓冲区,但现有的缓冲区与创建的子缓冲区在底层数组层面上是数据共享的,也就是说,子缓冲区相当于是现有缓冲区的

一个视图窗口。调用 slice() 方法可以创建一个子缓冲区

public void testSlice() {
    ByteBuffer byteBuffer = ByteBuffer.allocate(10);
    // 缓冲区的数据为 0-9
    for (int i = 0; i < byteBuffer.capacity(); i++) {
        byteBuffer.put((byte) i);
    }
    // 创建子缓冲区
    byteBuffer.position(3);
    byteBuffer.limit(7);
    ByteBuffer slice = byteBuffer.slice();

    // 改变子缓冲区的大小
    for (int i = 0; i < slice.capacity(); i++) {
        byte b = slice.get(i);
        b *= 10;
        slice.put(i, b);
    }

    byteBuffer.position(0);
    byteBuffer.limit(byteBuffer.capacity());
    while (byteBuffer.hasRemaining()) {
        System.out.println(byteBuffer.get());
    }
}
4.5.2 只读缓冲区

只读缓冲区非常简单,可以读取它们,但是不能向它们写入数据。可以通过调用缓冲区的 asReadOnlyBuffer()方法,将任何常规缓冲

区转换为只读缓冲区,这个方法返回一个与原缓冲区完全相同的缓冲区,并与原缓冲区共享数据,只不过它是只读的。如果原缓冲区的内

容发生了变化,只读缓冲区的内容也随之发生变化。

4.5.3 直接缓冲区

直接缓冲区是为加快 I/O 速度,使用一种特殊方式为其分配内存的缓冲区,JDK 文档中的描述为:给定一个直接字节缓冲区,Java 虚拟机

将尽最大努力直接对它执行本机 I/O 操作,也就是说,它会在每一次调用底层操作系统的本机 I/O 操作之前(或之后),尝试避免将缓冲区

的内容拷贝到一个中间缓冲区中或者从一个中间缓冲区中拷贝数据。要分配直接缓冲区,需要调用 allocateDirect() 方法,而不是

allocate()方法,使用方式与普通缓冲区并无区别。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Ambition0823

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值