buffer之 flip与rewind

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了buffer之 flip与rewind相关的知识,希望对你有一定的参考价值。

  在Buffer类中,有两个这样的方法:flip和rewind。查阅他们的API文档可以看到如下说明:

flip:

   public final Buffer flip()
    Flips this buffer. The limit is set to the current position and then the position is set to zero. If the mark is defined then it is discarded.
 
 
rewnd:
      public final Buffer rewind()
    Rewinds this buffer. The position is set to zero and the mark is discarded.
 
说明:
  针对buffer类的这三个方法的区别在哪?为什么要有这三个方法?我们首先来解决第一个问题,简单地说flip:将limit设置为当前位置,将position设置为起始位置,也就是0;
clear方法,将位置设置为0,将limit设置为buffer的capacity,也就是这个buffer的容量。那么,rewind方法,则是将position设置为0,也就是初始位置。这就是他们三个的区别;
 
举个栗子:
/*
  FileChannel fc=new FileInputStream("demo.txt").getChannel();//demo.txt是你本地上存在的一个文件
  ByteBuffer buff=ByteBuffer.allocate(1024);//这里的1024,就是buffer的capacity
 
  fc.read(buff);//将内容读从流中读取到buffer中
  //1.flip 如果使用的是flip,也就是将position设置为0,limit设置为当前位置,则输出的就是demo.txt中的内容
   //buff.flip();
 
  //2.rewind如果是rewind,也就是仅仅将position设置为0,而并不会改变limit,如果原先的limit在哪则文件输出就到哪(limit默认在buffer末端);输出的将是整个buffer的内容
  //buff.rewind();
 
  //输出buffer中的内容,这里需要解码才能正确显示
  System.out.println(Charset.forName("encoding").decode(buff));
  System.out.println();
  
*/
 
 

以上是关于buffer之 flip与rewind的主要内容,如果未能解决你的问题,请参考以下文章

java.nio.ByteBuffer 以及flip,clear及rewind区别

java.nio.ByteBuffer中flip,rewind,clear方法的区别

网络I/o编程模型5 Nio之buffer的操作和常用方法

Buffer flip()方法用法

Buffer flip()方法用法

Buffer flip()方法用法