您的位置:首页 > Web前端

Java NIO之Buffer中flip()、rewind()、clear()方法解析

2017-03-18 14:52 405 查看

1、flip()

public final Buffer flip() {
limit = position;//将当前的position位置赋值给limit
position = 0;//将position赋值为0,即归位
mark = -1;
return this;
}


2、rewind()

public final Buffer rewind() {
position = 0;//只是将position归位,limit不变
mark = -1;
return this;
}


3、clear()

public final Buffer clear() {
position = 0;//将position归位
limit = capacity;//将capacity赋值给limit,使limit归位
mark = -1;
return this;
}


4、示意图



5、实例

import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;

public class TestNIO {
public static void main(String[] args) {
ByteBuffer buf = ByteBuffer.allocate(1024);

buf.put("whataya want from me".getBytes());

buf.put(", as long as you love me".getBytes());

buf.flip();

buf.put("1234567".getBytes());

buf.rewind();

while (buf.hasRemaining())
System.out.print((char) buf.get());

buf.clear();

while (buf.hasRemaining())
System.out.print(() buf.get());
}
}


运行结果:

1234567 want from me, as long as you love me

1234567 want from me, as long as you love me…后面有许多空格填充

Process finished with exit code 0
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签:  nio java buffer