首页 > 文章列表 > java中Buffer是什么

java中Buffer是什么

java Buffer
236 2022-08-06

1、概念

使用Java NIO Buffers与NIO Channel交互。从Channel中读取数据到buffers里,从Buffer把数据写入到Channels必须对Buffer的三个属性进行控制,即capacities能力、position-location、limit限制。

2、实例

public static void main(String[] args) {
        //生成一个长度为10的缓冲区
        IntBuffer intBuffer = IntBuffer.allocate(10);
        for (int i = 0; i < intBuffer.capacity(); ++i){
            int randomNum = new SecureRandom().nextInt(20);
            intBuffer.put(randomNum);
        }
        //状态翻转
        intBuffer.flip();
        while (intBuffer.hasRemaining()){
            //读取数据
            System.out.print(intBuffer.get() + ",");
        }
        //clear方法本质上并不是删除数据
        intBuffer.clear();
        System.out.print("\n");
        System.out.println("-----------------------------");
        while (intBuffer.hasRemaining()){
            System.out.print(intBuffer.get() + ",");
        }
    }

本教程操作环境:windows7系统、java10版,DELL G3电脑。