java:BIO, NIO

 

BIO面向流.         阻塞式

 NIO面向缓冲区. 非阻塞式

 channnel负责传输,   buffer负责存储.

import java.nio.ByteBuffer;

public class TestBuffer {

    public static void main(String[] args) {
            TestBuffer.test2();
    }

    public static void test2() {
        String str = "abcde";
        ByteBuffer buf = ByteBuffer.allocate(1024);

        buf.put(str.getBytes());

        buf.flip();
        byte[] dst = new byte[buf.limit()];
        buf.get(dst,0,2);
        System.out.println(new String(dst,0,2));
        System.out.println(buf.position());

        buf.mark(); // 标记
        buf.get(dst,2,2);
        System.out.println(new String(dst,2,2));

        buf.reset(); // 恢复到mark的位置
        System.out.println(buf.position());

        // 判断缓冲区中是否有剩余数据
        if(buf.hasRemaining()){
            // 获取缓冲区中可以操作的数量
            System.out.println(buf.remaining());
        }
    }

    public static void test1(){
        String str = "abcde";

        //1. 分配一个指定大小的缓冲区
        ByteBuffer buf = ByteBuffer.allocate(1024);

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

        // 2. 利用put()存入数据到缓冲区
        buf.put(str.getBytes());

        // 3. 切换到读取数据模式
        buf.flip();

        // 4. 利用get()读取缓冲区数据
        byte[] dst = new byte[buf.limit()];
        buf.get(dst);
        System.out.println(new String(dst,0,dst.length));

        //5. rewind():可重复读
        buf.rewind();

        // 6. clear清空缓冲区。但缓冲区中的数据依然存在。
        buf.clear();

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

直接缓冲区域,非直接缓冲区

 直接缓冲区域:通过allocate()方法分配缓冲区,将缓冲区建立再jvm的内存中。

 非直接缓冲区:通过allocateDirect()方法分配直接缓冲区,将缓冲区建立在物理内存中。可以提高效率。

 通道(channel)

  channel本身不能直接访问数据,channel只能与buffer进行交互。

  

猜你喜欢

转载自blog.csdn.net/m0_37564426/article/details/113361804
今日推荐