欢迎您访问程序员文章站本站旨在为大家提供分享程序员计算机编程知识!
您现在的位置是: 首页

Netty之NIO基础-ByteBuffer

程序员文章站 2022-04-24 10:52:23
...

ByteBuffer

创建一个普通的Maven项目

package com.kevin.netty;

import java.io.FileInputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class TestBuffer {

    public static void main(String[] args) {
        //FileChannel
        try (FileChannel channel = new FileInputStream("data.txt").getChannel()) {
            ByteBuffer buffer = ByteBuffer.allocate(10);
            while (true){
                int read = channel.read(buffer);
                if (read==-1){
                    break;
                }
                buffer.flip(); //读模式
                while (buffer.hasRemaining()){
                    byte b = buffer.get();
                    System.out.println((char) b);
                }
                //
                buffer.clear();
            }

        } catch (IOException e) {
        }
    }
}

相关依赖

 <dependencies>
        <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.18.20</version>
        </dependency>

        <dependency>
            <groupId>com.google.code.gson</groupId>
            <artifactId>gson</artifactId>
            <version>2.8.7</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>
    </dependencies>

ByteBuffer正确使用姿势

  • 向buffer写入数据,调用channel.read(buffer)
  • 调用flip()切换到读模式
  • 从buffer中读取数据,调用buffer.get()
  • 调用clear()和compact()切换到写模式
  • 重复上面4个步骤

ByteBuffer结构

  • capacity 总容量
  • position 当前位置
  • limit 可用容量