Code Example 1
[1] fixed length . Upon completion of task assignment, its capacity can not be dynamically expanded or contracted, when an object to be encoded is greater than ByteBuffer POJO capacity index bounds exception occurs.
[2] identifies the location of only one pointer position . Literacy is the need to manually flip and rewind, etc., need to be very careful with these API, it will easily lead to abnormal.
[3] limited API function . Does not support the use of some advanced features require the user to achieve.
import java.nio.ByteBuffer;
public class JDKByteBufferTest {
public static void main(String[] args) {
// 初始化ByteBuffer
ByteBuffer buffer = ByteBuffer.allocate(20);
System.out.println(String.format(
"##### position:%s limit:%s remaining:%s", buffer.position(),
buffer.limit(), buffer.remaining()));
// put操作
String msg = "xy";
buffer.put(msg.getBytes());
System.out.println(String.format(
"##### position:%s limit:%s remaining:%s", buffer.position(),
buffer.limit(), buffer.remaining()));
// flip操作
buffer.flip();
System.out.println(String.format(
"##### position:%s limit:%s remaining:%s", buffer.position(),
buffer.limit(), buffer.remaining()));
// 获取值,读取的内容从position->limit
byte[] array = new byte[buffer.remaining()];
buffer.get(array);
String result = new String(array);
System.out.println("result is " + result);
System.out.println(String.format(
"##### position:%s limit:%s remaining:%s", buffer.position(),
buffer.limit(), buffer.remaining()));
}
}
##### position:0 limit:20 remaining:20
##### position:2 limit:20 remaining:18
##### position:0 limit:2 remaining:2
result is xy
##### position:2 limit:2 remaining:0
2 icon
3 JDK ByteBuffer limitations
[1] fixed length . Upon completion of task assignment, its capacity can not be dynamically expanded or contracted, when an object to be encoded is greater than ByteBuffer POJO capacity index bounds exception occurs.
[2] identifies the location of only one pointer position . Literacy is the need to manually flip and rewind, etc., need to be very careful with these API, it will easily lead to abnormal.
[3] limited API function . Does not support the use of some advanced features require the user to achieve.