buffer之 flip与rewind

时间:2022-05-25 00:13:04

  在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