[JAVA] [NIO] 4. Java NIO Buffer, javaniobuffer

Source: Internet
Author: User

[JAVA] [NIO] 4. Java NIO Buffer, javaniobuffer

The Buffer of Java NIO is used to interact with the channel.
Buffer is essentially a memory block. You can write data and read it out.
This memory block is packaged through the NIO Buffer object, which provides a series of methods to make access to the memory block easier.

Basic Buffer usage

To read and write data using Buffer, follow these steps:
1. Write Data to the Buffer
2. Call the buffer. flip () method.
3. read data from Buffer
4. Call the buffer. clear () method or the buffer. compact () method.

When you write data to the buffer, it records how much data you write. Once you read the data, you need to reverse the buffer and use the flip method to convert the buffer from the write mode to the Read mode. In Read mode, buffer allows you to read all written data.

Once you read all the data, you need to clear the buffer and make it ready for writing again. There are two ways: clear () or compact (). Clear clears the entire buffer, and compact only clears the data you have read. Other unread data will be moved to the buffer header, and the data to be written will be after the unread data.

Instance:

Pay attention to the calling sequence of flip and clear in the code.

Buffer capacity, position, and limit

Buffer has three attributes, as shown above
Position and limit depend on whether the Buffer is in read or write mode. The Capacity-independent mode is always the same.
View a chart

Capacity

Buffer has a fixed size, which is called capacity. You can also write data of the capacity byte type, long integer type, and character type into the buffer. Once the buffer is full, you need to leave it empty (read or clear) before writing data ).

Position

When you write data into the Buffer, it will write to a position. Position is initially 0. When the data is written, the position points to the position where the data is inserted. The maximum position value is capacity-1.
When you read data from the Buffer, you also read data from a position. When you flip a buffer from the write mode to the Read mode, the position is reset to 0. When reading data, the position also keeps moving, pointing to the next read location.

Limit

In write mode, limit indicates how much data you can write, which is equal to the capacity of the buffer.
When flip is in write mode, limit indicates how much data you can read. Therefore, when flip is in Read mode, limit is set to position in write mode. In other words, you can read all written data.

Buffer Types

Java NIO provides the following Buffer types:
· ByteBuffer
· MappedByteBuffer
· CharBuffer
· DoubleBuffer
· FloatBuffer
· IntBuffer
· LongBuffer
· Protocol Buffer
These Buffer types represent different data types. MappedByteBuffer will be discussed in subsequent chapters.

Allocating a Buffer

To obtain a Buffer object, you must first allocate a space. Each Buffer class has an allocate method.

ByteBuffer buf = ByteBuffer. allocate (48 );

CharBuffer buf = CharBuffer. allocate (1024 );

Writing Data to a Buffer

There are two ways to write data to buffer:
1. Write Data from channel to buffer
2. Write Data to yourself using the buffer put Method

Int bytesRead = inChannel. read (buf); // read into buffer.

Buf. put (127 );

Flip ()

The flip method converts the buffer from the write mode to the Read mode. Call the flip method to set position to 0 and limit to the position just before position.
In other words, the position is the read position, and the limit is the maximum read limit.
As shown in:



Reading Data from a Buffer

The following two methods can be used to read data from the buffer:
1. read data from the buffer to the channel.
2. read data from yourself using the get Method

// Read from buffer into channel.
Int bytesWritten = inChannel. write (buf );

Byte aByte = buf. get ();

Rewind ()

This method sets position to 0, so you can re-read all data in the buffer. The limit remains unchanged and still indicates how much data can be read from the buffer.
As shown in:



Clear () and compact ()

Once you have read the buffer data, you must prepare the buffer again and use the clear or compact method.
The clear method sets position to 0 and limit to capacity. In other words, the buffer is cleared, and the data in the buffer is not cleared, but the mark tells you where to start writing data.

If there is any unread data, when you call the clear method, the data will be ignored. Cannot be recovered.

If you still have unread data but want to read it later, you can call compact instead of clear.

The compact method moves all unread data to the buffer header and sets the last position of the position unread data. limit = capacity. Currently, buffer is ready to write, but unread data is not overwritten.

Mark () and reset ()

You can use the mark method to mark the position in a buffer. Later, you can use the reset method to set the position you just marked.

Buffer. mark ();
// Call buffer. get () a couple of times, e.g. during parsing.
Buffer. reset (); // set position back to mark.

Equals () and compareTo ()

Compare whether two buffers are equal.

Equals ()

If the two buffers are equal, the following conditions are met:
1. They have the same element type,
2. They have the same number of remaining elements and
3. The sequence of two residual elements (not related to their starting position) is point-by-point.

Compare the remaining buffer content.

CompareTo ()

This method compares the remaining elements of the buffer and meets the following conditions, indicating that one buffer is smaller than the other buffer.
1. The first unequal element is smaller than the corresponding element in the other buffer.
2. All elements are equal, but the first buffer consumes more than the second buffer (the first buffer has fewer elements)
The method for comparing two byte buffers is to compare the remaining Element Sequences in alphabetical order, regardless of the starting position of each sequence in its corresponding buffer.

The above explanation is obscure and difficult to understand. Let's look at an example.

ByteBuffer b1 = ByteBuffer. allocate (6 );
ByteBuffer b2 = ByteBuffer. allocate (6 );
Byte [] byte1 = new byte [] {1, 3 };
Byte [] byte2 = new byte [] {1, 2 };
B1.put (byte1 );
B2.put (byte2 );
System. out. println (b1.equals (b2 ));
System. out. println (b1.compareTo (b2 ));

True
0
Although the content of byte1 and byte2 is different, the rest content of b1 and b2 is the same and the type is the same, so equals = true, so compareTo = 0

Please do it yourself !!

Next section: [JAVA] [NIO] 5. Java NIO Scatter/Gather

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.