For the buffer zone, the most important operation is the read/write operation. The buffer zone provides two methods to read and write data in the buffer zone:Get,PutMethod andArrayMethod. WhileGet,PutThere are three methods to read and write data: read and write a single data in order, read and write a single data block at a specified location. In addition to the preceding methods for reading and writing data,CharBufferClass also providesPutAndAppendMethod. The read/write buffer methods are described in this article and later.
AlthoughAllocateThe buffer created by the method does not allocate memory space at a time, but we can think of a buffer as a length from the user's perspective.Capacity. When a buffer is created, the size of the buffer is the same as that of the array (CapacityValue. The following code creates6The Byte buffer.
ByteBuffer byteBuffer = ByteBuffer. allocate ( 6 );
ForByteBufferFor example, you can only access the data of six bytes belonging to the buffer zone. If the data exceeds this range,BufferOverflowExceptionException. This is a runtime error because it can only be found when the program is running.
Since the buffer zone is similar to the array, the buffer zone can identify the current position like an array. BufferPositionThe method provides us with this function.PositionMethods can be overloaded in two ways. Their definitions are as follows:
Public Final Int Position ()
Public Final Buffer position ( Int NewPosition)
The first overload is used to obtain the current position of the buffer. After creating a buffer,PositionThe initial value is0That is, the position of the first element in the buffer zone. After reading an element from the buffer,PositionValue addition1. We can see from this point that,PositionThe position returned by the method is the position of the currently readable element.PositionValue range from0ToCapacity-1. IfPositionThe value is equalCapacity, Indicating that no data is readable in the buffer zone.
PositionYou can set the current position of the buffer in the second overload mode of the method. ParametersNewPositionThe value range is0 <= newPosition <capacity. IfNewPositionThe value of is out of this range,PositionMethod will throwIllegalArgumentExceptionException.
In most cases, you do not need to directly control the buffer location. The method provided by the buffer class for reading and writing data can automatically set the current location of the buffer. In the buffer class,GetAndPutThis method is used to read and write data in the buffer.GetAndPutThe method is defined as follows:
ByteBufferClassGetAndPutMethod:
Public Abstract Byte Get ()
Public Abstract ByteBuffer put ( Byte B)
IntBufferClassGetAndPutMethod:
Public Abstract Int Get ()
Public Abstract IntBuffer put ( Int I)
Of the other five buffer classesGetAndPutThe method definition is similar to the preceding definition,GetMethod return