Java Network Programming from entry to mastery (34): Read and Write Data in the buffer-read and write a single data in sequence using the get and put Methods

Source: Internet
Author: User
Tags rewind

For the buffer zone, the most important operation is the read/write operation. The buffer provides two methods to read and write data in the buffer: Get, put, and array. The get and put methods can read and write data in three ways: read and write a single data in order, read and write a single data block at a specified position. In addition to the preceding methods for reading and writing data, the charbuffer class also provides put and append methods for writing strings. In this article and laterArticleThe read/write buffer methods are described respectively.

Although the buffer created using the allocate method does not allocate memory space at a time, we can think of a buffer as an array of capacity length from the user's perspective. After a buffer is created, the size (capacity value) of the buffer cannot be changed, and data outside the buffer cannot be accessed. See the followingCodeA 6-byte buffer is created.

Bytebuffer = bytebuffer. allocate (6); For bytebuffer, only six bytes of data belonging to this buffer zone can be accessed. If the data exceeds this range, a bufferoverflowexception exception will be thrown, which is a runtime error, because this error can only be found inProgramDetected during running.

Since the buffer zone is similar to the array, the buffer zone can identify the current position like an array. The position method of the buffer zone provides us with this function. The position method has two overload forms. 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 a buffer is created, the initial position value is 0, that is, the position of the first element in the buffer. After an element is read from the buffer, the value of position is added to 1. From this point, we can see that the position returned by the position method is the position of the currently readable element. The value range of position is from 0 to capacity-1. If the position value is equal to capacity, no data is readable in the buffer.

The second overload of the position method can be used to set the current position of the buffer. The value range of newposition is 0 <= newposition <capacity. If the value of newposition exceeds this range, the position method throws an illegalargumentexception exception.

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, the get and put methods are used to read and write data in the buffer. The get and put methods are defined as follows:

The get and put methods of the bytebuffer class:

Public abstract byte get ()
Public abstract bytebuffer put (byte B)
Get and put methods of the intbuffer class:

Public abstract int get ()
Public abstract intbuffer put (int I)
The get and put methods in the other five buffer classes are similar to the above definition, but the get method returns the corresponding data type, while the put method parameters are the corresponding data type, and the return value type is the corresponding buffer class.

Every time the put method writes a data to the buffer, the current position of the buffer is increased by 1. If the current position of the buffer is equal to capacity, a java. NiO. bufferoverflowexception exception is thrown when the put method is called. Areas not assigned a value in the buffer zone will be filled with 0. You can use the get method to obtain the data at the current position of the buffer and Add 1 to the current position of the buffer. Like the put method, when the current buffer location is equal to capacity, the get method will throw a java. NiO. bufferoverflowexception exception. The initial status of the buffer is 1.

 

Figure 1 initial status of the buffer zone

As shown in figure 1, the current position and data in the buffer zone are both 0 at the beginning of the buffer zone creation. When the following statement is used to write data to the buffer, the current status of the buffer is 2.

Bytebuffer. Put (byte) 2 );
Bytebuffer. Put (byte)-1 );

Figure 2 Current Status of the buffer
When the current position of the buffer is 3, the above bufferoverflowexception exception will be thrown by using the put and get methods.

 

Figure 3 the current position is at the end of the buffer
If you want to use the get method to obtain the specified data in the buffer, you must move the current location of the buffer to the specified location. We can use the position method to move the current location to any location in the buffer. The following code sets the current position of the buffer shown in Figure 3 to 2 and uses the get method to obtain the data of Location 2:

Bytebuffer. Position (2 );
System. Out. println (bytebuffer. Get (); the above Code will output 3. In addition to the position method, you can also use the rewind method to set the current position of the buffer to 0. The rewind method is defined as follows:

Public final buffer rewind (): Call the rewind method in the buffer State shown in Figure 2 to obtain the buffer state of 4.

 

Figure 4 buffer status after the rewind method is called
Next let's execute the following statement:

System. Out. println (bytebuffer. Get (); the buffer status is 5.

 

Figure 5 buffer status after the get method is called
In addition to position and capacity, the buffer also provides an identifier to restrict the accessible range of the buffer. This ID is limit. Like limit and position, two overload methods are also provided in the buffer class. Used to obtain and set the limit value. The Limit Method is defined as follows:

 

Public final int limit ()
Public final buffer limit (INT newlimit)
In the initial state, the buffer's limit and capacity values are the same. However, the difference between limit and capacity is that limit can be set through the limit method, and capacity has been specified when the buffer is created and cannot be changed. (In the value range of the newposition parameter of the position method mentioned above, it is said that it is 0 <= newposition <capacity. In fact, strictly speaking, it should be 0 <= newposition <limit) limit is of the same nature as capacity. Set the limit value to 2 in the buffer State shown in figure 5, and it is changed to the State shown in figure 6.

 

Figure 6 set limit to the buffer state of 2
When the position value is equal to limit, the current data in the buffer zone cannot be accessed, that is, the get and put methods cannot be used. Otherwise, a bufferoverflowexception exception is thrown. Since the buffer created using allocate does not allocate memory space at a time, you can set the buffer capacity to a large value, such as 10 m. If the buffer size is too large, the system performance may be reduced in some environments (such as in a PDA or smart Transplanter). Therefore, you can use the limit method to limit the buffer size based on the actual situation. Of course, limit can also represent the actual data volume in the buffer, which will be explained later. The following code demonstrates how to use the Limit Method to enumerate data in the buffer zone:

While (bytebuffer. Position () <bytebuffer. Limit ())
System. Out. println (bytebuffer. Get (); we can also use the flip and hasremaining methods to override the above Code. The flip method sets limit to the current location of the buffer. When limit is equal to position, the hasremaining method returns false, and true. The flip and hasremaining methods are defined as follows:

 

Public final buffer flip ()
Public final Boolean hasremaining ()
The following code demonstrates how to use the hasremaining method to enumerate data in the buffer:

While (bytebuffer. hasremaining ())
System. Out. println (bytebuffer. Get (); if you use the PUT Method to write data to the buffer in sequence from the first position of the buffer, use the flip method after writing the data. In this way, the value of limit is equal to the actual data volume in the buffer. You can use this method to set the end position of data when passing data in the network.

To review the above content, the following code summarizes the methods for creating a buffer, reading and writing data in the buffer, and setting the limit and position of the buffer.

Package net;

Import java. NiO .*;

Public class getputdata
{
Public static void main (string [] ARGs)
{
// Four methods for creating a buffer
Intbuffer = intbuffer. Allocate (10 );
Bytebuffer = bytebuffer. allocatedirect (10 );
Charbuffer = charbuffer. Wrap ("abcdefg ");
Doublebuffer = doublebuffer. Wrap (New Double [] {1.1, 2.2 });

// Write data to the buffer
Intbuffer. Put (0, 1000 );
Intbuffer. Put (0, 2000 );

System. Out. println ("current position of intbuffer:" + intbuffer. Position ());

Intbuffer. position (1); // set the current position of the buffer to 1
System. Out. println (intbuffer. Get (); // output the current data of the buffer.

Intbuffer. Rewind (); // set the current position of the buffer to 0
System. Out. println (intbuffer. Get (); // output the current data of the buffer.

Bytebuffer. Put (byte) 20 );
Bytebuffer. Put (byte) 33 );
Bytebuffer. Flip (); // set limit to position. Here it is 2
Bytebuffer. Rewind ();
While (bytebuffer. hasremaining () // enumerate data in bytebuffer
System. Out. Print (bytebuffer. Get () + "");

While (charbuffer. hasremaining () // enumerate data in charbuffer
System. Out. Print (charbuffer. Get () + "");

// Enumerate data in doublebuffer
While (doublebuffer. Position () <doublebuffer. Limit ())
System. Out. Print (doublebuffer. Get () + "");

}
}
Running result:

Current position of intbuffer: 2
2000
1000
20 33 a B C D E F G 1.1 2.2

Note: If you must use the buffer size to read data in the buffer, try not to use capacity, but use limit. Try not to write the following code:

While (bytebuffer. Position () <bytebuffer. Capacity ())
System. Out. println (bytebuffer. Get (); this is because when limit is less than capacity, the above Code will throw a bufferunderflowexception exception.

This article from the csdn blog, reproduced please indicate the source: http://blog.csdn.net/nokiaguy/archive/2009/10/09/4682908.aspx

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.