Java NIO (3) Buffer

Source: Internet
Author: User
Tags compact rewind

Java NIO Buffer

Java NiO buffers is used when interacting with NIO Channels. As you know, the data is read from channels to buffers, and written from buffers to channels.

A buffer is essentially a block of memory to which you can write data, which you can then later read again. This memory block was wrapped in a NIO Buffer object, which provides a set of methods that makes it easier Memory block.

Basic Buffer Usage

Using A to Buffer read and write data typically follows this little 4-step process:

    1. Write data into the Buffer
    2. Pagerbuffer.flip()
    3. Read data out of the Buffer
    4. Call buffer.clear() orbuffer.compact()

When you write data to a buffer, the buffer keeps track of how much data are written. Once need to read the data, you need to switch the buffer from writing mode into reading mode using the flip() method ca ll. In reading mode the buffer lets your read all the data written into the buffer.

Once you has read all of the data, you need to clear the buffer and to make it ready for writing again. You can do this in both Ways:by calling clear() or by calling compact() . The clear() method clears the whole buffer. The method is only clears the data which and you have compact() already read. Any unread data was moved to the beginning of the buffer, and data would now being written into the buffer after the unread dat A.

Here are a simple Buffer usage example, with the write, flip, read and clear operations maked in bold:

Buffer capacity, Position and Limit

A buffer is essentially a block of memory to which you can write data, which you can then later read again. This memory block was wrapped in a NIO Buffer object, which provides a set of methods that makes it easier Memory block.

A have Buffer three properties you need to is familiar with, in order to understand how a Buffer works. These is:

    • Capacity
    • Position
    • Limit

The meaning of and depends on whether the are in position limit Buffer read or write mode. Capacity always means the same, no matter the buffer mode.

Illustration of capacity, position and limit in write and read modes. The explanation follows in the sections after the illustration.

Buffer capacity, position and limit in write and read mode.
Capacity

Being a memory block, a Buffer has a certain fixed size, also called its "capacity". You can only write capacity bytes, longs, chars etc. into the Buffer. Once the Buffer is full and you need to empty it (read the data, or clear it) before you can write more data into it.

Position

When you write data Buffer to the, you do so at a certain position. Initially the position is 0. When a byte, long etc. have been written into the the the the position are advanced to point to the Buffer next cell in the buffer to Insert data into. Position can maximally become capacity - 1 .

When you read the data from a, you also the from Buffer a given position. When your flip a from Buffer writing mode to reading mode, the position are reset back to 0. As you read data from Buffer position the "Do" from, and are advanced to position next position to read.

Limit

In write mode the limit of a is the limit of what Buffer much data can write into the buffer. In write mode the limit is equal to the capacity of the Buffer .

When flipping Buffer the to read mode, limit means the limit of how much data can read from the data. Therefore, when flipping a into Buffer read mode, limit was set to write position of the write mode. In other words, you can read as many bytes as were written (limit was set to the number of bytes written, which is marked B Y position).

Buffer Types

Java NIO comes with the following Buffer types:

    • Bytebuffer
    • Mappedbytebuffer
    • Charbuffer
    • DoubleBuffer
    • Floatbuffer
    • Intbuffer
    • Longbuffer
    • Shortbuffer

As can see, these Buffer types represent different data types. In other words, they-let's work with the bytes in the buffer as char, short, int, long, float or double instead.

MappedByteBufferthe is a bit special, and would be covered in its own text.

Allocating a Buffer

To obtain a Buffer object must first allocate it. Every class has a method that is Buffer allocate() does this. Example showing ByteBuffer the allocation of a, with a capacity of bytes:

Bytebuffer buf = Bytebuffer.allocate (48);

Example allocating a with space for CharBuffer 1024x768 characters:

Charbuffer buf = charbuffer.allocate (1024);
Writing Data to a Buffer

You can write data to a in Buffer ways:

    1. Write data from A to Channel aBuffer
    2. Write data into Buffer the yourself, via the buffer ' s put() methods.

Here's an example showing how a Channel can write data into a Buffer :

int // read into buffer.

Here's an example this writes data into a Buffer via the put() method:

There is many other versions put() of the method, allowing you to write data into the the Buffer many different ways. For instance, writing at specific positions, or writing a array of bytes into the buffer. See the JAVADOC for the concrete buffer implementation for more details.

Flip ()

The flip() method switches a from Buffer writing mode to Reading mode. Calling flip() sets position the back to 0, and sets the limit where position just was.

In other words, now position marks the reading position, and limit marks how many bytes, chars etc. were written into the BUF Fer-the limit of how many bytes, chars etc. so can be read.

Reading Data from a Buffer

There is ways you can read data from a Buffer .

    1. Read data from the buffer into a channel.
    2. Read data from the buffer yourself, using one of the Get () methods.

Here's an example of how can read data from a buffer into a channel:

// read from buffer into channel. int byteswritten = inchannel.write (BUF);

Here's an example, reads data from a Buffer using the Get () method:

byte abyte = Buf.get ();

There is many other versions get() of the method, allowing your to read data from the in Buffer many different ways. For instance, reading at specific positions, or reading a array of bytes from the buffer. See the JAVADOC for the concrete buffer implementation for more details.

Rewind ()

Buffer.rewind() position The sets the back to 0 so that you can reread all the data in the buffer. limitthe remains untouched, thus still marking how many elements (bytes, chars etc.) that can is read from the Buffer .

Clear () and compact ()

Once You is done reading data out of the the the the and the the You has to make the-ready for Buffer Buffer writing again. You can do the either by calling clear() or by calling compact() .

If you are set back to 0 and the clear() position limit capacity . In and words, the is Buffer cleared. The data in the are not Buffer cleared. Only the markers telling where can write data into the is Buffer .

If There is any unread data Buffer in the When you call clear() that data would be ' forgotten ', meaning you no longer has a NY markers telling what data have been read, and what have not been read.

If There is still unread data Buffer in the, and you want to read it later, but you need to do some writing first, call instead of clear() .

compact()Copies all unread data to the beginning of the Buffer . Then it sets the last position unread element. limitThe property was still set capacity to, just like clear() does. Now Buffer the are ready for writing, and you'll not overwrite the unread data.

Mark () and Reset ()

You can mark a given position in a by Buffer calling the Buffer.mark() method. You can then later reset the position back to the marked position by calling the Buffer.reset() method. Here are an example:

Buffer.mark (); // Call Buffer.get () A couple of times, e.g. during parsing. Buffer.reset ();   // set position back to mark.
Equals () and CompareTo ()

It is possible to compare, buffers using equals() and compareTo() .

Equals ()

Buffers is equal if:

    1. They is of the same type (byte, char, int etc.)
    2. They has the same amount of remaining bytes, chars etc. in the buffer.
    3. All remaining bytes, chars etc. is equal.

As can see, Equals is only compares part Buffer of the and not every single element inside it. In fact, it just compares the remaining elements in the Buffer .

CompareTo ()

compareTo()The method compares the remaining elements (bytes, chars etc.) of the of the buffers, for use in e.g. sorting routines. A buffer is considered "smaller" than another buffer if:

    1. The first element which is equal to the corresponding element with the other buffer, was smaller than that in the other Buffe R.
    2. All elements is equal, but the first buffer is runs out of elements before the second buffer does (it has fewer elements).

Java NIO (3) Buffer

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.