Netty——ByteBuffer的基本使用

x33g5p2x  于2022-07-20 转载在 其他  
字(2.0k)|赞(0)|评价(0)|浏览(121)

一、ByteBuffer 正确使用的步骤

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

二、ByteBuffer的基本使用示例

1.1、pom.xml文件引入依赖

<dependency>
            <groupId>io.netty</groupId>
            <artifactId>netty-all</artifactId>
            <version>4.1.39.Final</version>
        </dependency>
        <dependency>
            <groupId>org.projectlombok</groupId>
            <artifactId>lombok</artifactId>
            <version>1.16.18</version>
        </dependency>
        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.5</version>
        </dependency>
        <dependency>
            <groupId>com.google.guava</groupId>
            <artifactId>guava</artifactId>
            <version>19.0</version>
        </dependency>
        <dependency>
            <groupId>ch.qos.logback</groupId>
            <artifactId>logback-classic</artifactId>
            <version>1.2.3</version>
        </dependency>
        <dependency>
            <groupId>com.google.protobuf</groupId>
            <artifactId>protobuf-java</artifactId>
            <version>3.11.3</version>
        </dependency>

1.2、创建test.txt文件

1.3、示例代码

package com.example.nettytest.nio.day1;

import lombok.extern.slf4j.Slf4j;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

/**
 * @description:
 * @author: xz
 * @create: 2022-07-18 22:17
 */
@Slf4j
public class TestByteBuffer {
    public static void main(String[] args) {
        //FileChannel
        try (FileChannel channel = new FileInputStream("test.txt").getChannel()) {
            //allocate:分配一个新的字节缓冲区,容量为10
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while(true){
                // 从 channel 读取数据,向 buffer 写入
                int len = channel.read(buffer);
                log.info("读取到的字节数 {}", len);
                if(len ==-1){
                    break;
                }
                // 打印 buffer 的内容
                buffer.flip();// 切换至读模式
                while (buffer.hasRemaining()){// 是否还有剩余未读数据
                    byte b = buffer.get();
                    log.info("实际字节 {}", (char) b);
                }
                buffer.clear(); // 切换为写模式
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}

1.4、输出结果

相关文章