本文主要是介绍Java NIO之Buffer中flip()、rewind()、clear()方法解析,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
1、flip()
public final Buffer flip() {limit = position;//将当前的position位置赋值给limitposition = 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
这篇关于Java NIO之Buffer中flip()、rewind()、clear()方法解析的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!