NIO Buffer代码示例
程序员文章站
2022-04-24 10:35:36
...
Buffer的代码示例
import java.nio.ByteBuffer;
import org.junit.Test;
public class TestBuffer {
@Test
public void testBuffer() {
//创建一个缓冲区
ByteBuffer buf = ByteBuffer.allocate(1024);
//打印参数
System.out.println("-----------------------------------");
System.out.println(buf.capacity());
System.out.println(buf.limit());
System.out.println(buf.position());
buf.put("hello".getBytes());
System.out.println("-----------------------------------");
System.out.println(buf.capacity());
System.out.println(buf.limit());
System.out.println(buf.position());
buf.flip();
System.out.println("-----------------------------------");
System.out.println(buf.capacity());
System.out.println(buf.limit());
System.out.println(buf.position());
byte[] dest = new byte[buf.limit()];
//
// buf.get(dest);
//
// System.out.println(new String(dest));
buf.get(dest,0,2);
System.out.println(new String(dest));
System.out.println(buf.position());
buf.mark();
System.out.println("-----------------------------------");
buf.get(dest,2,2);
System.out.println(new String(dest));
System.out.println(buf.position());
buf.reset();
System.out.println(buf.position());
}
}
转载于:https://my.oschina.net/ikiru/blog/1536639