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

NIO Buffer代码示例

程序员文章站 2022-04-24 10:35:36
...

Buffer的代码示例

NIO中buffer

import java.nio.ByteBuffer;

import org.junit.Test;

public class TestBuffer {

    @Test
    public void testBuffer() {
        //创建一个缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);
        //打印参数
        System.out.println("-----------------------------------");
        System.out.println(buf.capacity());
        System.out.println(buf.limit());
        System.out.println(buf.position());

        buf.put("hello".getBytes());

        System.out.println("-----------------------------------");
        System.out.println(buf.capacity());
        System.out.println(buf.limit());
        System.out.println(buf.position());

        buf.flip();

        System.out.println("-----------------------------------");
        System.out.println(buf.capacity());
        System.out.println(buf.limit());
        System.out.println(buf.position());

        byte[] dest = new byte[buf.limit()];
//      
//      buf.get(dest);
//      
//      System.out.println(new String(dest));

        buf.get(dest,0,2);
        System.out.println(new String(dest));

        System.out.println(buf.position());

        buf.mark();

        System.out.println("-----------------------------------");

        buf.get(dest,2,2);

        System.out.println(new String(dest));

        System.out.println(buf.position());

        buf.reset();

        System.out.println(buf.position());
    }

}

转载于:https://my.oschina.net/ikiru/blog/1536639