Java NiO 缓冲区学习笔记

  一、缓冲区(Buffer):在 Java NIO 中负责数据的存取。缓冲区就是数组。用于存储不同数据类型的数据

        根据数据类型不同(boolean 除外),提供了相应类型的缓冲区:  ByteBuffer、 CharBuffer、ShortBuffer、 IntBuffer、 LongBuffer、FloatBuffer、 DoubleBuffer

        上述缓冲区的管理方式几乎一致,通过 allocate() 获取缓冲区,如 ByteBuffer.allocate(1024);

二、    缓冲区存取数据 核心方法 put() 存入数据到缓冲区中  ;get() 获取缓冲区中的数据


三、缓冲区的核心属性:

       capatity 容量 缓冲区最大存储数据容量,一旦声明不能改变 ;
        limit:界限,表示缓冲区可以操作数据的大小(limit后数据不能进行读写)
        position 位置,表示缓冲区正在操作数据的位置
        mark :标记 表示记录当前 position 的位置。可以通过 reset() 恢复到 mark 的位置      

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

代码实例

    public void test1(){
   String str="abcde";
   //分配指定大小的缓冲区
ByteBuffer buf=ByteBuffer.allocate(1024);
        System.out.println("");
       //存数据
        buf.put(str.getBytes());
        System.out.println("put");
      System.out.println(buf.position());
      System.out.println(buf.limit());
      System.out.println(buf.capacity());
      
      //切换读数据模式
      buf.flip();
      //利用get读取缓冲区数据
      byte[] dst=new byte[buf.limit()];
      buf.get(dst);
      System.out.println(new String(dst,0,dst.length)); 
      System.out.println("get");
      System.out.println(buf.position());
      System.out.println(buf.limit());
      System.out.println(buf.capacity());
      
      //rewind 可重复读
      buf.rewind();
      System.out.println("rewind");
      System.out.println(buf.position());
      System.out.println(buf.limit());
      System.out.println(buf.capacity());
      
      //clear 清空缓冲区,但是缓冲区数据依然存在
      buf.clear();
      System.out.println("clear");
      System.out.println(buf.position());
      System.out.println(buf.limit());
      System.out.println(buf.capacity());
   }

public void test2(){
   String str="abcde";
   ByteBuffer buf=ByteBuffer.allocate(1024);
   buf.put(str.getBytes());
  //切换读模式
   buf.flip();
   byte[] bst=new byte[buf.limit()];
   buf.get(bst,0,2);
   System.out.println(new String(bst,0,2));
   System.out.println(buf.position());
   //mark标记
   buf.mark();
   buf.get(bst,2,2);
   System.out.println(new String(bst,2,2));
   System.out.println(buf.position());
   //reset :恢复到mark的位置
   buf.reset();
   System.out.println(buf.position());
     }

扫描二维码关注公众号,回复: 4255342 查看本文章


猜你喜欢

转载自blog.csdn.net/xiaosong_2016/article/details/78767247
今日推荐