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