package nio;
import java.nio.ByteBuffer;
public class BufferTest {
public static void main(String[] args) throws InterruptedException {
ByteBuffer buf = ByteBuffer.allocate(9);
System.out.println("初始capacity = " +buf.capacity());
System.out.println("初始position = " + buf.position());
System.out.println("初始limit = " + buf.limit());
System.out.println("初始mark = " + buf.mark());
buf.put("123456789".getBytes());
System.out.println("put写之后的position = " + buf.position());
System.out.println("put写之后的limit = " + buf.limit());
System.out.println("put写之后的mark = " + buf.mark());
buf.flip();//put写之后要flip,将position置为0,将limit置为写入的最后一个元素(待操作的下一个元素)所在的索引位置
System.out.println("flip之后的position = " + buf.position());
System.out.println("flip之后的limit = " + buf.limit());
System.out.println("flip之后的mark = " + buf.mark());
/*
while(buf.hasRemaining()){
System.out.println("#" + (char)buf.get());
}
System.out.println("get之后的position = " + buf.position());
System.out.println("get之后的limit = " + buf.limit());
System.out.println("get之后的mark = " + buf.mark());
*/
for(int i = 0 ; i <= 3; i++ ){
System.out.println("#" + (char)buf.get());
}
System.out.println("部分get读之后的position = " + buf.position());
buf.compact();
System.out.println("compact之后的position = " + buf.position());
System.out.println("compact之后的limit = " + buf.limit());
System.out.println("compact之后的mark = " + buf.mark());
buf.put("abcd".getBytes());
buf.flip();
while(buf.hasRemaining()){
System.out.println("#" + (char)buf.get());
}
buf.clear();
System.out.println("clear之后的position = " + buf.position());
System.out.println("clear之后的limit = " + buf.limit());
System.out.println("clear之后的mark = " + buf.mark());
}
}