多语言展示
当前在线:1016今日阅读:27今日分享:41

java8新特性ByteBuffer方法clear,mark如何使用

java8新特性ByteBuffer方法clear如何使用
方法/步骤
1

clear()方法:清空缓冲区。但是缓冲区的数据依然存在,但是这些数据处于被遗忘的状态。package com.gwolf;import org.junit.Test;import java.nio.ByteBuffer;public class TestBuffer {    @Test    public void test1(){        //分配一个指定大小的缓冲区        ByteBuffer byteBuffer = ByteBuffer.allocate(1024);        System.out.println('----------allocate()-------------');        System.out.println(byteBuffer.position());        System.out.println(byteBuffer.limit());;        System.out.println(byteBuffer.capacity());                //利用put方法存入数据到缓冲区中        String str = 'abcde';        byteBuffer.put(str.getBytes());                System.out.println('----------put()-------------');        System.out.println(byteBuffer.position());        System.out.println(byteBuffer.limit());;        System.out.println(byteBuffer.capacity());                //3、切换成读取数据模式        byteBuffer.flip();        System.out.println('----------flip()-------------');        System.out.println(byteBuffer.position());        System.out.println(byteBuffer.limit());;        System.out.println(byteBuffer.capacity());                //4、利用get()读取缓冲区的数据        byte[] dst = new byte[byteBuffer.limit()];        byteBuffer.get(dst);        System.out.println(new String(dst,0,dst.length));                byteBuffer.clear();        System.out.println('----------clear()-------------');        System.out.println(byteBuffer.position());        System.out.println(byteBuffer.limit());;        System.out.println(byteBuffer.capacity());            }}

2

查看执行clear方法之后position、limit、capacity的位置大小

3

创建一个ByteBuffer,代码如下:public void test2() {        ByteBuffer buffer = ByteBuffer.allocate(1024);        buffer.put('abced'.getBytes());                buffer.flip();        byte[] dst = new byte[buffer.limit()];        buffer.get(dst,0,2);        System.out.println(new String(dst,0,2));                System.out.println(buffer.position());    }

4

查看打印结果。

5

mark()方法:标识记录当前position的位置,可以通过reset()回复到mark的位置。         buffer.mark();        buffer.get(dst,2,2);        System.out.println(new String(dst,2,2));        System.out.println(buffer.position());

6

查看现在position的位置是多少

7

使用reset()恢复到mark位置buffer.reset();System.out.println(buffer.position());

推荐信息