NIO(二)

Mark和reset的使用

package com.cppdy.nio;

import java.nio.ByteBuffer;

//Mark和reset的使用
public class NIOBufferDemo1 {

    public static void main(String[] args) {

        ByteBuffer buf = ByteBuffer.allocate(1024);

        // 放入5个
        buf.put("cppdy".getBytes());
        System.out.println("开启读的模式:");
        // 开启读
        buf.flip();

        byte[] bytes = new byte[buf.limit()];
        
        System.out.println("mark之前取两个值:");
        buf.get(bytes,0,2);
        System.out.println("position:" + buf.position());
        System.out.println("limit:" + buf.limit());
        System.out.println("capacity" + buf.capacity());

        buf.mark();
        System.out.println("mark之后取两个值:");
        buf.get(bytes,2,2);
        System.out.println("position:" + buf.position());
        System.out.println("limit:" + buf.limit());
        System.out.println("capacity" + buf.capacity());
        
        buf.reset();
        System.out.println("reset之后的值:");
        System.out.println("position:" + buf.position());
        System.out.println("limit:" + buf.limit());
        System.out.println("capacity" + buf.capacity());
        
        System.out.println("reset之后取两个值:");
        buf.get(bytes,2,2);
        System.out.println("position:" + buf.position());
        System.out.println("limit:" + buf.limit());
        System.out.println("capacity" + buf.capacity());
    }

}

reset之后position会回到mark位置

posted @ 2018-11-29 22:12  知识追求者  阅读(137)  评论(0编辑  收藏  举报