- release
- Update
- read
Buffer
Buffer (Buffer) responsible for the data stored in the Java NIO. Buffer is an array. For storing an array of different data types.
Depending on the type of data (except the boolean type), a type of a corresponding buffer.
ByteBuffer(常用)、CharBuffer、ShortBuffer、IntBuffer、LongBuffer、FloatBuffer、DoubleBuffer
Above the buffer management almost identical, they are () Gets the buffer zone allocate.
Two core buffer access method of the data
put (): the data stored into the buffer
get (): Gets the data buffer
Buffer four core attributes
capacity: capacity, maximum storage capacity of the buffer represents, once declared, can not be changed.
limit: limit, it represents the buffer size of data can be operated. (Behind the limit data can not be read)
position: position, represents the buffer location of the data being operated on. position <= limit <= capacity
mark: mark indicates the recording position of the current position, can be restored to the position mark by just reset ()
Read data buffer
1. Allocate a specified buffer size
1, the maximum capacity of 1024
2, the boundaries of 1024
3, the position of 0
1 |
ByteBuffer buffer=ByteBuffer.allocate(1024); |
2. The method of use put into the stored data to the buffer
1, the maximum capacity of 1024
2, the boundaries of 1024
3, position 5
1 |
buffer.put("abcde".getBytes()); |
3. Switch to read data mode flip Method
1, the maximum capacity of 1024
2, the limits of 5
3, the position of 0
1 |
buffer.flip(); |
4. A method of reading data using the get buffer
1, the maximum capacity of 1024
2, the limits of 5
3, position 5
1 |
byte [] by=new byte[buffer.limit()]; |
The read data is repeated using rewind
1, the maximum capacity of 1024
2, the limits of 5
3, the position of 0
1 |
buffer.rewind(); |
6. empty the buffer, the buffer data is still, the state data is forgotten
1, the maximum capacity of 1024
2, the boundaries of 1024
3, the position of 0
1 |
buffer.clear(); |
Buffer mark (marker) to be used
mark () method for marking the current position of the position
reset () method to return to the position of the marker position
1 |
|
Buffer's slice method
sliceBuffer created by their common data slice method only one, or by modifying the original Buffer sliceBuffer will be reflected on another Buffer.
1 |
ByteBuffer byteBuffer=ByteBuffer.allocate(10); |
程序运行结果
只读Buffer
我们可以随时将一个普通Buffer调用asReadOnlyBuffer方法返回一个只读Buffer,但不能将只读Buffer转换为一个读写Buffer
1 |
ByteBuffer byteBuffer=ByteBuffer.allocate(10); |
直接缓冲区和非直接缓冲区
非直接缓冲区:通过allocate() 方法分配缓冲区,将缓冲区建立在JVM的内存中。
直接缓冲区:通过allocateDirect() 方法分配直接缓冲区,将缓冲区建立在操作系统的物理内存中,可以提高效率。
非直接缓冲区
Direct buffers
Original: Big Box NIO buffer (Buffer) data storage